package vn.sunnet.backviet01.game.coloa.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Timer;

import java.util.TimerTask;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.anddev.andengine.entity.modifier.AlphaModifier;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.MoveModifier;
import org.anddev.andengine.entity.modifier.MoveXModifier;
import org.anddev.andengine.entity.modifier.MoveYModifier;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.ScaleAtModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.CameraScene;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.menu.MenuScene;
import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.anddev.andengine.entity.scene.menu.item.IMenuItem;
import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.anddev.andengine.entity.shape.RectangularShape;
import org.anddev.andengine.entity.sprite.BaseSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.text.Text;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ClickDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.util.HorizontalAlign;
import org.anddev.andengine.util.MathUtils;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Toast;

import vn.sunnet.backviet01.game.coloa.AuLac.AnDuongVuong;
import vn.sunnet.backviet01.game.coloa.AuLac.Arrow;
import vn.sunnet.backviet01.game.coloa.AuLac.CaoLo;
import vn.sunnet.backviet01.game.coloa.AuLac.DichHuTong;
import vn.sunnet.backviet01.game.coloa.AuLac.General;
import vn.sunnet.backviet01.game.coloa.animated.skill.AnimatedSkill;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillBangHa;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillDaiMocTran;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillDragon;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillLieuNguyenHoa;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillLoiQuangDien;
import vn.sunnet.backviet01.game.coloa.animated.skill.SkillToaDiaChan;
import vn.sunnet.backviet01.game.coloa.constant.Constants;
import vn.sunnet.backviet01.game.coloa.constant.Constants.GameStates;
import vn.sunnet.backviet01.game.coloa.human.enemy.Aurra;
import vn.sunnet.backviet01.game.coloa.human.enemy.BloodLine;
import vn.sunnet.backviet01.game.coloa.human.enemy.DoThu;
import vn.sunnet.backviet01.game.coloa.human.enemy.DoThuMagic;
import vn.sunnet.backviet01.game.coloa.human.enemy.Enemy;
import vn.sunnet.backviet01.game.coloa.human.enemy.EnemyArrow;
import vn.sunnet.backviet01.game.coloa.human.enemy.FlatDragon;
import vn.sunnet.backviet01.game.coloa.human.enemy.Melee;
import vn.sunnet.backviet01.game.coloa.human.enemy.MinisterEnemy;
import vn.sunnet.backviet01.game.coloa.human.enemy.NhamNgao;
import vn.sunnet.backviet01.game.coloa.human.enemy.Range;
import vn.sunnet.backviet01.game.coloa.human.enemy.SoundCircle;
import vn.sunnet.backviet01.game.coloa.human.enemy.Spell;
import vn.sunnet.backviet01.game.coloa.human.enemy.Tank;
import vn.sunnet.backviet01.game.coloa.human.enemy.DoThu.DoThuStates;
import vn.sunnet.backviet01.game.coloa.human.enemy.FlatDragon.FlatDragonStates;
import vn.sunnet.backviet01.game.coloa.human.enemy.NhamNgao.NhamNgaoStates;
import vn.sunnet.backviet01.game.coloa.interfaces.ISkill;
import vn.sunnet.backviet01.game.coloa.store.GameStore;
import vn.sunnet.backviet01.game.coloa.store.GeneralStore;
import vn.sunnet.backviet01.game.coloa.util.Contain;
import vn.sunnet.backviet01.game.coloa.util.CoolDown;
import vn.sunnet.backviet01.game.coloa.util.CoolDownCallEnemy;
import vn.sunnet.backviet01.game.coloa.util.CoolDownRecoverBlood;
import vn.sunnet.backviet01.game.coloa.util.CoolDownRecoverMana;
import vn.sunnet.backviet01.game.coloa.util.ItemMenu;
import vn.sunnet.backviet01.game.coloa.util.MyAnimatedButton;
import vn.sunnet.backviet01.game.coloa.util.MyCamera;
import vn.sunnet.backviet01.game.coloa.util.MyRadioButton;
import vn.sunnet.backviet01.game.coloa.util.MyScene;
import vn.sunnet.backviet01.game.coloa.util.MySkillButton;
import vn.sunnet.backviet01.game.coloa.util.MySprite;
import vn.sunnet.backviet01.game.coloa.util.MyTiledButton;
import vn.sunnet.backviet01.game.coloa.util.SkillMenu;
import vn.sunnet.backviet01.game.coloa.util.Contain.StateSkill;
import vn.sunnet.backviet01.game.coloa.util.MyAnimatedButton.OnButtonClickListener;
import vn.sunnet.backviet01.game.coloa.util.MyTiledButton.OnTiledButtonClickListener;
import vn.sunnet.backviet01.game.coloa.util.mypool.ArrowOfRangePool;
import vn.sunnet.backviet01.game.coloa.util.mypool.ArrowPool;
import vn.sunnet.backviet01.game.coloa.util.mypool.DoThuMagicPool;
import vn.sunnet.backviet01.game.coloa.util.mypool.SoundCirclePool;
import vn.sunnet.backviet01.game.coloa.util.mypool.SpritesPool;
import vn.sunnet.util.remoteconfig.ConfigClient;
import vn.sunnet.util.remoteconfig.ConfigNode;
import vn.sunnet.util.security.InvalidChecksumException;
import vn.sunnet.util.ui.SunnetLoadParam;

public class MainGame extends LayoutGameAcitivy implements
		IOnSceneTouchListener, IScrollDetectorListener, IClickDetectorListener,
		IOnMenuItemClickListener, OnButtonClickListener, OnTiledButtonClickListener/*, ILoadItemEvent,
		IPaymentEvent, IQplayHighScore, IQplayAchievementListener*/ {

	private float mCameraWidth = Constants.CAMERA_WIDTH;
	private float mCameraHeight = Constants.CAMERA_HEIGHT;

	private static final float[] yPosEnemyStart = { Constants.Y_FIRST_LINE,
			Constants.Y_SECOND_LINE, Constants.Y_THIRD_LINE,
			Constants.Y_FOURTH_LINE, Constants.Y_FIVETH_LINE };

	public static final int SKILL_LIEU_NGUYEN_HOA = 1;
	public static final int SKILL_HAN_BANG_TIEN = 2;
	public static final int SKILL_BANG_HA = 3;
	public static final int SKILL_MOC_TIEN = 4;
	public static final int SKILL_DAI_MOC_TRAN = 5;
	public static final int SKILL_LOI_QUANG_DIEN = 6;
	public static final int SKILL_TOA_TRAN_DIA = 7;

	private static final int RESET_ACCOUNT_1 = Constants.ACCOUNT_01 + 50;
	private static final int RESET_ACCOUNT_2 = RESET_ACCOUNT_1 + 1;
	private static final int RESET_ACCOUNT_3 = RESET_ACCOUNT_1 + 2;
	private static final int YES_POPUP = 53;
	private static final int NO_POPUP = 54;

	private static final int UP_STRENG = 0;
	private static final int UP_AGILITY = 1;
	private static final int UP_INTEL = 2;
	private static final int UP_COMPLETE = 3;
	private static final int UP_WARNING = 5;

	private static final int BUY_SKILL_POINT = 6;
	private static final int BUY_BASIC_POINT = 7;
	private static final int BUY_SNAIL = 8;
	private static final int CONTAIN_SNAIL = 9;

	private static final int PLAY_GAME = 10;
	private static final int SELECT_SKILL = 11;
	private static final int SELECT_ITEM = 12;

	private static final int EXIT_BOARD_PRICE = 14;

	private static final int DESTROY = 105;
	private static final int SALE = 106;
	private static final int PLUS = 107;
	private static final int UP = 108;

	private static final int DESTROY_REMOVE = 109;
	private static final int COMPLETE_REMOVE = 110;
	private static final int CHECK_REMOVE_0 = 111;
	private static final int CHECK_REMOVE_1 = 112;
	private static final int CHECK_REMOVE_2 = 113;
	private static final int BUY_REMOVE_SKILL_POPUP = 114;
	private static final int EXIT_REMOVE_SKILL_POPUP = 115;
	private static final int DETAIL_REMOVE_SKILL = 116;
	private static final int PAY_SNAIL_REMOVE_SKILL_POPUP = 117;
	private static final int SCROLL_LEFT = 118;
	private static final int SCROLL_RIGHT = 119;

	private static final String[] Name_Shop = { "Hỏa tiễn", "Liêu nguyên hỏa",
			"Hàn băng tiễn", "Băng hà", "Mộc tiễn", "Đại mộc trấn",
			"Huyền thiết tiễn", "Lôi quang điện", "Thổ tiễn", "Tỏa chấn địa",
			"Mộc nỏ", "Trúc nỏ", " Đồng nỏ", "Thiết nỏ",
			"Linh quang kim \r\n trảo thần nỏ", "Thiết khôi", "Ngân khôi",
			"Hoàng kim khôi", "Mộc giáp", "Đồng giáp", "Hoàng nguyên giáp",
			"Đồng trảo", "Thiết trảo", "Kim trảo" };

	private static final int[] EXP_LEVEL = { 70, 250, 500, 1025, 1625, 3000,
			4500, 6200, 9250, 12500, 16000, 20000, 24500, 28500, 33400, 38000,
			44000, 50500, 57500, 64500, 72000, 80000 };

	// ====================================================================================//
	// SOUND
	// ====================================================================================//

	private GameStates mGameStates = GameStates.GAME_NORMAL;

	private CoolDown mArrowCoolDown;

	private Sound sArrowShoot;
	private Sound sArrowGoal;
	private Sound sButtonClicked;
	private Sound sDestroyIce;
	private Sound sFireSkill;
	private Sound sArrowGoalCityWall;
	private Sound sDoThuSkill;
	private Sound sSkillTree;
	private Sound sDragonFireSkill;
	private Sound sGameOver;
	private Sound sIceSkill;
	private Sound sLightSkill;
	private Sound sSword;
	private Sound sCityWallBroken;
	private Sound sWinGame;
	private Sound sTransitionScene;
	private Sound sWallHit;
	private Sound sEarthquake;
	private Sound sSpellAttack;

	private Music mDrum;
	private Music mSpellFlying;
	private Music mBackgroundMusic;
	private Music mEnemyMove;
	private Music mMenuMusic;

	private boolean isDrum;
	private boolean isSpellFlying;
	private boolean isEnemyMove;

	public static final String TAG = "CoLoa";

	private boolean isMainGameScene = false;
	private boolean isAccountScene = false;
	private boolean isLockMainScene = false;

	private int totalGold = 0;
	private float countGoldGamePlay = 0;

	/***
	 * MainGameScene
	 */

	private static final float TAN_2 = 0.06f;
	private static final float TAN_3 = 0.08f;

	private int ACCOUNT = -1;

	private long DELAY_ARROW_TIME;
	private float VELOCITY_ARROW;

	private float VELOCITY_X_NHAMNGAO;
	private float VELOCITY_X_MELEE;
	private float VELOCITY_X_AURRA;
	private float VELOCITY_X_RANGE;
	private float VELOCITY_X_SPELL;
	private float VELOCITY_X_TANK;

	private long TIMEPEREACHFRAME_ENEMY_DIE;
	private long TIMEPEREACHFRAME_MELEE_MOVE;
	private long TIMEPEREACHFRAME_MELEE_SPAB;
	private long TIMEPEREACHFRAME_RANGE_FIRE;
	private long TIMEPEREACHFRAME_RANGE_MOVE;
	private long TIMEPEREACHFRAME_TANK_MOVE;
	private long TIMEPEREACHFRAME_TANK_SPAB;

	private int stage = 0;
	private int lastGameStage = 0;
	private int[] callMinisterEnemy;

	private float ATTACK_AURRA;
	private float ATTACK_MELEE;
	private float ATTACK_RANGE;
	private float ATTACK_SPELL;
	private float ATTACK_TANK;

	private float GENERAL_HP;
	private float GENERAL_MANA;

	private float HP_AURRA;
	private float HP_MELEE;
	private float HP_RANGE;
	private float HP_SPELL;
	private float HP_TANK;

	private float EXP_AURRA;
	private float EXP_MELEE;
	private float EXP_RANGE;
	private float EXP_SPELL;
	private float EXP_TANK;

	private long timeStartGame = 0;
	private long countTimeGame;

	private float xTouch;
	private float yTouch;
	private float xTouchMoveItem;
	private float yTouchMoveItem;
	private float xSkill;
	private float ySkill;

	private boolean isFire;
	private boolean isSkill;
	private boolean isTouch;
	private int idSkilllUse = -1;
	private int button = -1;

	private int totalArrow = 1;
	private int useArrowSkill = -1;
	private int buttonArrow = -1;
	private float useManaArrowSkill = 0;

	private boolean isRunning = false;
	private boolean isPause = false;

	private boolean isFissured = false;

	private MyCamera mCamera;
	private CameraScene pauseGameScene;
	private CameraScene resultScene;
	private MyScene mMainScene;
	private HUD hud;

	TextureRegion mEndOfFinishTexture;
	BitmapTextureAtlas mEndOfFinishBitmapTextureAtlas;
	BitmapTextureAtlas mBackgroundBitmapTextureAtlas;
	BitmapTextureAtlas mMeleeRangeTextureAtlas;
	BitmapTextureAtlas mCitywallBitmapTextureAtlas;
	BitmapTextureAtlas mMagicBitmapTextureAtlas;
	BitmapTextureAtlas mOtherBitmapTextureAtlas;
	BitmapTextureAtlas mWinTextureAtlas;
	BitmapTextureAtlas mGameOverTextureAtlas;
	BitmapTextureAtlas mPauseItemTextureAtlas;
	BitmapTextureAtlas mEquipBitmapAtlas;
	BitmapTextureAtlas mTankSpellBitmapTextureAtlas;
	BitmapTextureAtlas mAurraBitmapAtlas;
	BitmapTextureAtlas mEnemyFreezed;

	BitmapTextureAtlas mToaDiaChanBitmapAtlas;
	BitmapTextureAtlas mBangHaMocBitmapAtlas;
	BitmapTextureAtlas mLieuNguyenHoaBitmapAtlas;
	BitmapTextureAtlas mLoiQuangDienBitmapAtlas;

	// =====================//
	// ICON SKILL
	// =====================//
	private TextureRegion[] mIconSkillListTextureRegion;
	private TextureRegion mBrightIconSkillTextureRegion;
	private TextureRegion mMaskIconSkillTextureRegion;
	private TextureRegion mPlusIconSkillTextureRegion;

	// Pause
	private TextureRegion mPauseBGTextureRegion;
	private TextureRegion mReplayTextureRegion;
	private TextureRegion mContinueTextureRegion;
	private TextureRegion mExitPauseTextureRegion;

	// ********************//
	// MINISTER ENEMY//
	// *******************//
	/*
	 * Dragon
	 */
	BitmapTextureAtlas mFlatDragonBitmapMove;
	BitmapTextureAtlas mFlatDragonBitmapAttack;
	BitmapTextureAtlas mFlyingDragonBitmapMove;
	BitmapTextureAtlas mFlyingDragonBitmapAttackDie;

	BitmapTextureAtlas mBeatBitmap;

	BitmapTextureAtlas mSkillFireDragonBitmap;

	private TiledTextureRegion mFlatDragonMoveTextureRegion;
	private TiledTextureRegion mFlatDragonAttackTextureRegion;
	private TiledTextureRegion mSkillFireDragonTextureRegon;

	/*
	 * Do Thu
	 */

	private BitmapTextureAtlas mDoThuBitmapTextureAtlas;

	private TiledTextureRegion mDoThuTextureRegion;

	private TextureRegion mDoThuSkillTextureRegion;

	private DoThuMagicPool mDoThuMagicPool;
	private ArrayList<DoThuMagic> mDoThuMagicList;

	/*
	 * Nham Ngao
	 */

	BitmapTextureAtlas mNhamNgaoBitmapAtlas;
	BitmapTextureAtlas mNhamNgaoBitmapAttackAtlas;
	private TiledTextureRegion mNhamNgaoMove;
	private TiledTextureRegion mNhamNgaoAttack;

	// Spell
	private TiledTextureRegion mSpellTiledTextureRegion;
	private TextureRegion mMagicTexture;
	private TiledTextureRegion mSpellFreezed;

	// Aurra
	private TiledTextureRegion mAurraMoveTiledTextureRegion;
	private TiledTextureRegion mAurraDieTiledTextureRegion;
	private TextureRegion mSoundCircleTextureRegion;
	private TiledTextureRegion mAurraFreezed;

	// Tank
	private TiledTextureRegion mTankMoveTextureRegion;
	private TiledTextureRegion mTankAttackTextureRegion;
	private TiledTextureRegion mTankDieTextureRegion;
	private TiledTextureRegion mTankFreezed;

	private TextureRegion mBloodPiece;
	private TextureRegion mBloodPieceFrame;

	private TiledTextureRegion mDaiMocTranTextureRegion;
	private TiledTextureRegion mLieuNguyenHoaTextureRegion;
	private TiledTextureRegion mBangHaTextureRegion;
	private TiledTextureRegion mToaDiaChanTextureRegion;
	private TiledTextureRegion mToaDiaChanChildTexture;
	private TiledTextureRegion mLoiQuangDienTextureRegion;

	private TextureRegion mBackgroundTRegion;

	private TextureRegion pauseButtonGameRegion;
	private TextureRegion winGameRegion;
	private TextureRegion gameOverRegion;
	private TextureRegion mTableWinGame;
	private TextureRegion mSnailTextureRegion;

	private TextureRegion[] mArrowsTRegion;
	private TextureRegion[] mCrossBowTRegion;
	private TextureRegion[] mSkillPassiveTextureRegion;

	private TextureRegion bloodRegion;
	private TextureRegion containRegion;
	private TextureRegion contain_enemyRegion;

	private TextureRegion manaRegion;
	private TextureRegion faceGeneralTextureRegion;
	private TextureRegion faceEnemyGeneralTextureRegion;
	private TextureRegion citywall_emergencyTextureRegion;
	private TextureRegion citywall_fireTextureRegion;

	private TextureRegion mMagic_circle;

	private TiledTextureRegion mMeleeRangeDieTRegion;
	private TiledTextureRegion mRangeTRegion_Fire;
	private TiledTextureRegion mRangeTRegion_Move;
	private TiledTextureRegion mMeleeTRegion_Move;
	private TiledTextureRegion mMeleeTRegion_Stab;
	private TextureRegion mArrowOfRangeTextureRegion;

	private TiledTextureRegion mMeleeFreezed;
	private TiledTextureRegion mRangeFreezed;

	private General mGeneral;
	private General[] mGeneralList;

	private Sprite winGame;
	private Sprite gameOver;
	private Sprite tableWinGame;
	private Sprite mSnailWin;
	private ChangeableText mStageWin;
	private ChangeableText mTotalEXP;
	private ChangeableText mTimeStage;
	private ChangeableText mBonusStage;
	private Sprite pause_button;
	private ChangeableText mBloodText;
	private ChangeableText mManaText;
	private ChangeableText mStageText;
	private ChangeableText mCoinText;

	private Text mGameOverText;
	private Text mWinText;

	private Sprite crossBow;
	private Sprite arrowFreeze;
	private Sprite background;

	private Sprite citywall;

	private MySkillButton[] mSkillButton;
	private Sprite magic_circle;
	private Sprite mana;
	private Sprite face_general;
	private Sprite face_enemyGeneral;
	private Sprite blood;
	private Sprite contain_blood;
	private Sprite contain_mana;
	private Sprite mSnailCoin;

	private Sprite contain_enemy;

	private GameStore gameStore;
	private GeneralStore generalStore;

	private ArrowPool mArrows;
	private SpritesPool mMagics;
	private SoundCirclePool mCircles;
	private ArrowOfRangePool mArrowOfRange;

	private ArrayList<String> mEnemyTool;
	private ArrayList<Integer> mCountMelee;
	private ArrayList<Integer> mCountRange;
	private ArrayList<Integer> mCountTank;
	private ArrayList<Integer> mCountAurra;
	private ArrayList<Integer> mCountSpell;
	private ArrayList<Long> mCoolDown;

	private ArrayList<AnimatedSkill> mISkillUse;
	private ArrayList<Arrow> mArrowsList;
	private ArrayList<Sprite> mMagicsList;
	private ArrayList<SoundCircle> mSoundCircleList;
	private ArrayList<EnemyArrow> mArrowOfRangeList;
	private ArrayList<Enemy> mEnemyList;

	private String crossBowName = null;
	private int crossBow_index = -1;

	private boolean isUpEnemy = false;
	private boolean isAurra = false;

	private int[] idSkillUse = new int[3];

	private String[] nameSkillUse = new String[3];

	// private Handler enemyHandler;

	/**
	 * EquipmentScene
	 */

	private CameraScene mInformationScene;
	private CameraScene mPriceSnailScene;
	private CameraScene mUpgradeGeneralScene;
	private MenuScene mRemoveSkillScene;

	private float mCamera_MinX = 0;

	private float mCamera_MaxY_ScrollItem = 0;
	private float mCamera_MinY_ScrollItem = 0;
	private float mCamera_MaxY_ScrollSkill = 0;
	private float mCamera_MinY_ScrollSkill = 0;

	private float mCamera_CurentX = 0;
	private float mCamera_CurentY = 0;

	private static final float PADDING = 5;

	private float pX = 492;
	private float pY = 65;

	// Scrolling
	private SurfaceScrollDetector mScrollDetector;
	private ClickDetector mClickDetector;

	private int totalItem = Constants.TOTAL_ITEM;
	private int totalSkill = Constants.TOTAL_SKILL;

	private int itemMoveable = -1;

	private boolean isSelect = false;
	private boolean isMoveItemToUse = false;
	private boolean isAcceptMoveItem = false;
	private boolean isUsedMove = false;
	private boolean isItemScroll = false;
	private boolean isSkillScroll = false;
	private boolean isGeneralScroll = false;
	private boolean isScrolling = false;
	private boolean isItemMenu = false;
	private boolean isMove = false;
	private boolean isInforScene = false;
	private boolean isLockScene = false;
	private boolean isUpgradeScene = false;
	private boolean isBuySnail = false;

	private boolean[] isSelectRemove;

	private boolean selectRemoveSkill = false;
	private boolean isRemoveSkill = false;

	private int MOVE = -1;
	private int CONTAIN_MOVE = -1;

	private int generalUse = 0;
	private int[] generalLastUsed;

	// ========//
	// Chon tuong
	// ========//

	private int[] reset = { RESET_ACCOUNT_1, RESET_ACCOUNT_2, RESET_ACCOUNT_3 };

	private MyScene mEquipmentScene;

	private ChangeableText totalGold_display = null;

	BitmapTextureAtlas mEquipmentOtherBitmap;
	BitmapTextureAtlas mBackgroundBitmap;
	BitmapTextureAtlas mListItemBitmap;
	BitmapTextureAtlas mListSkillBitmap;

	BitmapTextureAtlas mEquipmentRemoveSkillBitmap;

	BitmapTextureAtlas mGeneralBitmap;

	private TextureRegion mTaytuykinhTextureRegion;
	private TextureRegion mContainTaytuykinhTextureRegion;
	private TextureRegion mRemovableTextureRegion;
	private TextureRegion mRemovable_select_TextureRegion;

	private TiledTextureRegion mYesTiledTextureRegion;
	private TiledTextureRegion mNoTiledTextureRegion;
	private TiledTextureRegion mSkillSelectTextureRegion;
	private TiledTextureRegion mContainGoldTextureRegion;
	private TiledTextureRegion mUpgradeTiledTextureRegion;
	private TiledTextureRegion mPlusTiledTextureRegion;
	private TiledTextureRegion mBuyTiledTextureRegion;
	private TiledTextureRegion mPayTiledTextureRegion;
	private TiledTextureRegion mUseTiledTextureRegion;
	private TiledTextureRegion mReturnTiledTextureRegion;
	private TiledTextureRegion mSaleTiledTextureRegion;
	private TiledTextureRegion mBigReturnTiledTextureRegion;
	private TiledTextureRegion mDetailTiledTextureRegion;

	private TextureRegion mBackgroundTextureRegion;
	private TiledTextureRegion mPlayTextureRegionE;
	private TiledTextureRegion mItemSelectTextureRegion;

	private TextureRegion mBoardInfoSmall;
	private TextureRegion mBoardInfo;

	private TextureRegion mLockMenu;
	private TextureRegion mUnLockMenu;
	private TextureRegion mContainMenu;

	private TextureRegion mBackgroundSpliteGeneralTextureRegion;

	private TextureRegion mDichHuTongTextureRegion;
	private TextureRegion mCaoLoTextureRegion;
	private TextureRegion mAnDuongVuongTextureRegion;

	private TextureRegion mScrollTextureRegion;

	private Sprite background_equipment;
	private Sprite backgroundSplite;
	private Contain[] contain;

	private Sprite taytuykinh;

	private MyAnimatedButton play;
	private MyAnimatedButton select_skill;
	private MyAnimatedButton select_item;
	private MyAnimatedButton contain_gold;

	private MyRadioButton[] checkRemoveSkill;
	private MyAnimatedButton completeRemoveSkill;
	private Sprite taytuykinh_remove;
	private MyAnimatedButton destroy_remove;

	private Sprite[] mSkill_Remove;
	private Sprite[] mContain_Skill_Remove;

	private MyAnimatedButton buy;
	private MyAnimatedButton up;
	private MyAnimatedButton use;
	private MyAnimatedButton sale;
	private MyAnimatedButton returnSprite;

	private Sprite mBoardUpgrade;
	private MyAnimatedButton mWarningUpgrade;
	private MyAnimatedButton mPlusUpgradeStreng;
	private MyAnimatedButton mPlusUpgradeAgility;
	private MyAnimatedButton mPlusUpgradeIntel;
	private MyAnimatedButton mCompleteUpgrade;
	private ChangeableText pointStreng;
	private ChangeableText pointIntel;
	private ChangeableText pointAgility;
	private ChangeableText pointSkill;
	private ChangeableText pointBasic;

	private Sprite containTotalAssets;
	private Sprite containTaytuykinh;

	private Rectangle mContainInforItem;
	private Rectangle mContainInforSkill;

	private Sprite contain_index;

	private Sprite[] mGenerals;

	private MyTiledButton scrollLeft;
	private MyTiledButton scrollRight;

	private ChangeableText nameItem;
	private ChangeableText upAttackText;
	private ChangeableText upDefendText;
	private ChangeableText upStrengText;
	private ChangeableText upIntelText;
	private ChangeableText upArrowText;
	private ChangeableText upArrowVelocityText;
	private ChangeableText bounderyText;
	private ChangeableText priceText;

	private ChangeableText attackTextSkill;
	private ChangeableText bounderyTextSkill;
	private ChangeableText useManaTextSkill;
	private ChangeableText coolDownTextSkill;

	private ChangeableText pointSkillInfor;
	private ChangeableText levelSkillInfor;
	private ChangeableText timeDelayEnemy;

	private ChangeableText nextManaUse;
	private ChangeableText nextTurn;
	private ChangeableText nextDelayEnemy;
	private ChangeableText nextDamage;

	private Text mPointSkill;

	private Text text;
	private ChangeableText useGeneral;

	private Rectangle contain_select;

	private MySprite[] mListLockItemList;
	private MySprite[] mListLockSkillList;
	private MySprite[] mContainItemList;
	private MySprite[] mContainSkillList;
	private TextureRegion[] mListSkillTextureRegions;
	private SkillMenu[] mListSkillMenu;
	private TextureRegion[] mListItemTextureRegions;
	private ItemMenu[] mListItemMenu;

	private ItemMenu itemClicked = null;
	private SkillMenu skillClicked = null;

	private Sprite contain_selected = null;
	private Sprite item_selected = null;

	// private int[] ID_Skill_List_Store;
	private int[] ID_Item_List_Store;

	private String[] ID_Item_Data;
	private String[] ID_Skill_Data;

	private int[] ID_Skill_Use;
	private int[] ID_Item_Use;

	// private int[] ID_Item_Store;
	private int[] ID_Skill_Store;

	private boolean isBuy = false;
	private boolean isNeedPaySnail = false;
	private boolean isLearning = false;
	private boolean isUsedItem = false;
	private boolean isUsedSkill = false;

	private RectangularShape trans;

	// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// private int[] Streng_General;
	// private int[] Intell_General;
	private int[] Coin_General;

	private int[] gameAccountLevel;

	private MyScene mAccountScene;

	BitmapTextureAtlas mBackgroundAccount;
	BitmapTextureAtlas mAccountBitmap1;

	private TextureRegion mBackgroundAccountTextureRegion;
	private TextureRegion mContainAccountTextureRegion;
	private TextureRegion mContainAccountResetTextureRegion;

	private TextureRegion[] mGeneralIcon;
	private TextureRegion mDichHuTong_IconTextureRegion;
	private TextureRegion mCaoLo_IconTextureRegion;
	private TextureRegion mAnDuongVuong_IconTextureRegion;

	private TextureRegion mSnailCoinIcon;

	private Sprite background_Account;

	private MyTiledButton[] mAccountIcon;

	private MyTiledButton[] contain_account;

	private MyTiledButton[] mResetAccount;

	private ChangeableText[] countRetry;
	private ChangeableText[] generalLevelAccount;
	private ChangeableText[] generalName;
	private ChangeableText[] stageAccount;
	private ChangeableText[] timeAccount;

	// private ChangeableText[] HP_Text;
	// private ChangeableText[] MP_Text;
	private ChangeableText[] Coin_Text;

	private GameStore[] mGameSrotes;

	/**
	 * Khai bao MenuScene
	 */

	BitmapTextureAtlas mAllMenuBitmap;

	private MyScene mMenuScene;

	private MenuScene mStaticMenuScene;

	private TextureRegion mCoLoaTextureRegion;
	private TextureRegion mPlayTextureRegion;

	private TextureRegion mInfoTextureRegion;
	private TextureRegion mShareTextureRegion;
	private TextureRegion mMoreGameTextureRegion;
	private TextureRegion mExitTextureRegion;

	private Sprite mBGMenu;
	private Sprite mCoLoa_Logo;

	private SpriteMenuItem mPlayMenuItem;

	private SpriteMenuItem mInfoMenuItem;
	private SpriteMenuItem mShareMenuItem;
	private SpriteMenuItem mMoreGameMenuItem;
	private SpriteMenuItem mExitMenuItem;

	/**
	 * GameProcess
	 */
	public void onLoadComplete() {
	}

	public Engine onLoadEngine() {

		mCamera = new MyCamera(0, 0, mCameraWidth, mCameraHeight);

		this.hud = new HUD();
		mCamera.setHUD(hud);

		EngineOptions eo = new EngineOptions(true, ScreenOrientation.LANDSCAPE,
				new FillResolutionPolicy(), mCamera);
		eo.getRenderOptions().disableExtensionVertexBufferObjects();
		eo.getTouchOptions().setRunOnUpdateThread(true);
		eo.setNeedsMusic(true);
		eo.setNeedsSound(true);

		mEngine = new Engine(eo);

		return mEngine;
	}

	public void onLoadResources() {

		super.onLoadResources();
	}

	public Scene onLoadScene() {
		// mEngine.registerUpdateHandler(new FPSLogger());

		return super.onLoadScene();
	}

	private void onLoadResourcesMenu() {
		mAllMenuBitmap = new BitmapTextureAtlas(512, 512,
				TextureOptions.DEFAULT);
		mBackgroundAccount = new BitmapTextureAtlas(1024, 512,
				TextureOptions.NEAREST_PREMULTIPLYALPHA);

		mAccountBitmap1 = new BitmapTextureAtlas(1024, 512,
				TextureOptions.DEFAULT);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(mAccountBitmap1,
				this, "contain_name_account.png", 0, 0);
		mEngine.getTextureManager().loadTexture(mAccountBitmap1);

		mBackgroundAccountTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mBackgroundAccount, this,
						"background_account.png", 0, 0);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(mAllMenuBitmap,
				this, "textbg_menu.png", 0, 0);

		mCoLoaTextureRegion = new TextureRegion(mAllMenuBitmap, 0, 0, 369, 205);
		mPlayTextureRegion = new TextureRegion(mAllMenuBitmap, 0, 213, 253, 58);

		mInfoTextureRegion = new TextureRegion(mAllMenuBitmap, 370, 0, 44, 46);
		mShareTextureRegion = new TextureRegion(mAllMenuBitmap, 419, 0, 44, 46);
		mMoreGameTextureRegion = new TextureRegion(mAllMenuBitmap, 370, 48, 44,
				46);
		mExitTextureRegion = new TextureRegion(mAllMenuBitmap, 468, 0, 44, 46);

		mEngine.getTextureManager().loadTexture(mBackgroundAccount);
		mEngine.getTextureManager().loadTexture(mAllMenuBitmap);

	}

	private void onLoadResourcesMainGame() {

		// BimapAtlas
		mEndOfFinishBitmapTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mOtherBitmapTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mBackgroundBitmapTextureAtlas = new BitmapTextureAtlas(1024, 1024,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		;
		mMeleeRangeTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mMagicBitmapTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.DEFAULT);
		mWinTextureAtlas = new BitmapTextureAtlas(512, 512,
				TextureOptions.DEFAULT);
		mGameOverTextureAtlas = new BitmapTextureAtlas(512, 512,
				TextureOptions.DEFAULT);
		mEngine.getTextureManager().loadTexture(mGameOverTextureAtlas);
		mPauseItemTextureAtlas = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR);
		mEngine.getTextureManager().loadTexture(mPauseItemTextureAtlas);
		mCitywallBitmapTextureAtlas = new BitmapTextureAtlas(256, 512,
				TextureOptions.DEFAULT);
		mEquipBitmapAtlas = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mEngine.getTextureManager().loadTexture(mEquipBitmapAtlas);
		mAurraBitmapAtlas = new BitmapTextureAtlas(1024, 256,
				TextureOptions.DEFAULT);
		mEngine.getTextureManager().loadTexture(mAurraBitmapAtlas);

		mEnemyFreezed = new BitmapTextureAtlas(256, 256,
				TextureOptions.BILINEAR);
		mEngine.getTextureManager().loadTexture(mEnemyFreezed);

		mEndOfFinishTexture = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mEndOfFinishBitmapTextureAtlas, this,
						"end_of_start.png", 0, 0);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mPauseItemTextureAtlas, this, "pause_item.png", 0, 0);

		mPauseBGTextureRegion = new TextureRegion(mPauseItemTextureAtlas, 1, 1,
				510, 297);
		mReplayTextureRegion = new TextureRegion(mPauseItemTextureAtlas, 322,
				408, 106, 36);
		mContinueTextureRegion = new TextureRegion(mPauseItemTextureAtlas, 322,
				370, 122, 37);
		mExitPauseTextureRegion = new TextureRegion(mPauseItemTextureAtlas,
				322, 445, 80, 29);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(mEnemyFreezed,
				this, "enemy_freezed.png", 0, 0);

		mMeleeFreezed = new TiledTextureRegion(mEnemyFreezed, 0, 130, 50, 95,
				1, 1);
		mRangeFreezed = new TiledTextureRegion(mEnemyFreezed, 155, 0, 72, 80,
				1, 1);
		mSpellFreezed = new TiledTextureRegion(mEnemyFreezed, 93, 0, 57, 70, 1,
				1);
		mTankFreezed = new TiledTextureRegion(mEnemyFreezed, 0, 0, 92, 120, 1,
				1);
		mAurraFreezed = new TiledTextureRegion(mEnemyFreezed, 92, 81, 145, 150,
				1, 1);

		mTankSpellBitmapTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mEngine.getTextureManager().loadTexture(
				mTankSpellBitmapTextureAtlas);

		onLoadIconSkill();
		onLoadBangHaMoc();
		onLoadDaiMocTran();
		onLoadLieuNguyenHoa();
		onLoadToaDiaChan();
		onLoadLoiQuangDien();
		onLoadResourcesNhamNgao();
		onLoadResourcesDoThu();
		onLoadResourcesFlatDragon();
		loadCrossBowArrow();

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mAurraBitmapAtlas, this, "enemy_aurra.png", 0, 0);
		this.mAurraMoveTiledTextureRegion = new TiledTextureRegion(
				mAurraBitmapAtlas, 0, 87, 680, 169, 4, 1);
		this.mAurraDieTiledTextureRegion = new TiledTextureRegion(
				mAurraBitmapAtlas, 0, 0, 1020, 87, 6, 1);
		this.mSoundCircleTextureRegion = new TextureRegion(mAurraBitmapAtlas,
				685, 156, 200, 100);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mTankSpellBitmapTextureAtlas, this, "enemy_tank_spell.png", 0,
				0);
		this.mTankMoveTextureRegion = new TiledTextureRegion(
				mTankSpellBitmapTextureAtlas, 0, 0, 360, 200, 3, 2);
		this.mTankAttackTextureRegion = new TiledTextureRegion(
				mTankSpellBitmapTextureAtlas, 0, 204, 360, 308, 3, 2);
		this.mTankDieTextureRegion = new TiledTextureRegion(
				mTankSpellBitmapTextureAtlas, 374, 0, 624, 260, 4, 2);

		this.mSpellTiledTextureRegion = new TiledTextureRegion(
				mTankSpellBitmapTextureAtlas, 374, 263, 490, 249, 7, 3);
		this.mMagicTexture = new TextureRegion(mTankSpellBitmapTextureAtlas,
				800, 437, 60, 20);

		this.pauseButtonGameRegion = new TextureRegion(mAccountBitmap1, 895,
				450, 60, 60);
		this.mBloodPiece = new TextureRegion(mAccountBitmap1, 806, 390, 4, 4);
		this.mBloodPieceFrame = new TextureRegion(mAccountBitmap1, 960, 375,
				64, 4);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mCitywallBitmapTextureAtlas, this, "citywall.png", 0, 0);
		citywall_emergencyTextureRegion = new TextureRegion(
				mCitywallBitmapTextureAtlas, 0, 0, 128, 480);
		citywall_fireTextureRegion = new TextureRegion(
				mCitywallBitmapTextureAtlas, 128, 0, 128, 480);
		faceEnemyGeneralTextureRegion = new TextureRegion(mAccountBitmap1, 602,
				460, 41, 46);

		this.faceGeneralTextureRegion = new TextureRegion(mAccountBitmap1, 260,
				245, 77, 123);
		this.containRegion = new TextureRegion(mAccountBitmap1, 620, 372, 255,
				8);
		this.contain_enemyRegion = containRegion.deepCopy();
		this.bloodRegion = new TextureRegion(mAccountBitmap1, 790, 390, 8, 8);
		this.manaRegion = new TextureRegion(mAccountBitmap1, 772, 390, 8, 8);
		mTableWinGame = new TextureRegion(mAccountBitmap1, 520, 0, 504, 290);
		mSnailTextureRegion = new TextureRegion(mAccountBitmap1, 886, 388, 64,
				52);

		this.winGameRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mWinTextureAtlas, this, "win.png", 0, 0);
		this.gameOverRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mGameOverTextureAtlas, this, "game_over.png",
						0, 0);

		this.mBackgroundTRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mBackgroundBitmapTextureAtlas, this,
						"background01.png", 0, 0);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mMeleeRangeTextureAtlas, this,
				"enemy_range_melee_skill_icon.png", 0, 0);
		// /////////////////////////////////////////////////////////////////////////////////////////////////

		this.mMagic_circle = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mMagicBitmapTextureAtlas, this,
						"magic_circle.png", 128, 0);
		// /////////////////////////////////////////////////////////////////////////////////////////////////
		this.mMeleeTRegion_Move = new TiledTextureRegion(
				mMeleeRangeTextureAtlas, 0, 311, 616, 99, 7, 1);
		this.mMeleeTRegion_Stab = new TiledTextureRegion(
				mMeleeRangeTextureAtlas, 0, 413, 945, 103, 9, 1);

		this.mRangeTRegion_Move = new TiledTextureRegion(
				mMeleeRangeTextureAtlas, 0, 0, 512, 106, 8, 1);
		this.mRangeTRegion_Fire = new TiledTextureRegion(
				mMeleeRangeTextureAtlas, 0, 215, 864, 95, 9, 1);
		this.mArrowOfRangeTextureRegion = new TextureRegion(mEquipBitmapAtlas,
				410, 194, 60, 6);

		this.mMeleeRangeDieTRegion = new TiledTextureRegion(
				mMeleeRangeTextureAtlas, 0, 107, 580, 107, 8, 1);

		this.mCircles = new SoundCirclePool(this.mSoundCircleTextureRegion);
		this.mMagics = new SpritesPool(this.mMagicTexture);
		this.mArrows = new ArrowPool(this.mArrowsTRegion[0]);
		this.mArrowOfRange = new ArrowOfRangePool(
				this.mArrowOfRangeTextureRegion);

		mEnemyTool = new ArrayList<String>();
		mCountMelee = new ArrayList<Integer>();
		mCountRange = new ArrayList<Integer>();
		mCountTank = new ArrayList<Integer>();
		mCountSpell = new ArrayList<Integer>();
		mCountAurra = new ArrayList<Integer>();
		mCoolDown = new ArrayList<Long>();

		this.mEngine.getTextureManager().loadTexture(
				this.mOtherBitmapTextureAtlas);
		this.mEngine.getTextureManager().loadTexture(
				this.mBackgroundBitmapTextureAtlas);
		this.mEngine.getTextureManager().loadTexture(
				this.mMeleeRangeTextureAtlas);
		this.mEngine.getTextureManager().loadTexture(
				this.mMagicBitmapTextureAtlas);
		this.mEngine.getTextureManager().loadTexture(mWinTextureAtlas);
		this.mEngine.getTextureManager().loadTexture(
				mCitywallBitmapTextureAtlas);

	}

	// =================//
	// SKILL
	// =================//

	private void onLoadLieuNguyenHoa() {
		mLieuNguyenHoaBitmapAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mLieuNguyenHoaBitmapAtlas, this, "skill_lieu_nguyen_hoa.png",
				0, 0);
		mEngine.getTextureManager().loadTexture(mLieuNguyenHoaBitmapAtlas);

		mLieuNguyenHoaTextureRegion = new TiledTextureRegion(
				mLieuNguyenHoaBitmapAtlas, 0, 0, 880, 440, 4, 2);
	}

	private void onLoadLoiQuangDien() {
		mLoiQuangDienBitmapAtlas = new BitmapTextureAtlas(512, 256,
				TextureOptions.BILINEAR);

		mLoiQuangDienTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(mLoiQuangDienBitmapAtlas, this,
						"skill_light.png", 0, 0, 4, 1);

		mEngine.getTextureManager().loadTexture(mLoiQuangDienBitmapAtlas);
	}

	private void onLoadBangHaMoc() {
		if (mBangHaMocBitmapAtlas == null) {
			mBangHaMocBitmapAtlas = new BitmapTextureAtlas(1024, 512,
					TextureOptions.BILINEAR);
			BitmapTextureAtlasTextureRegionFactory.createFromAsset(
					mBangHaMocBitmapAtlas, this, "skill_bang_moc.png", 0, 0);
		}

		mEngine.getTextureManager().loadTexture(mBangHaMocBitmapAtlas);

		mBangHaTextureRegion = new TiledTextureRegion(mBangHaMocBitmapAtlas, 0,
				0, 925, 280, 5, 2);
	}

	private void onLoadDaiMocTran() {
		if (mBangHaMocBitmapAtlas == null) {
			mBangHaMocBitmapAtlas = new BitmapTextureAtlas(1024, 512,
					TextureOptions.BILINEAR);
			BitmapTextureAtlasTextureRegionFactory.createFromAsset(
					mBangHaMocBitmapAtlas, this, "skill_bang_moc.png", 0, 0);
		}
		mEngine.getTextureManager().loadTexture(mBangHaMocBitmapAtlas);
		mDaiMocTranTextureRegion = new TiledTextureRegion(
				mBangHaMocBitmapAtlas, 0, 335, 868, 90, 7, 1);
	}

	private void onLoadToaDiaChan() {
		this.mToaDiaChanBitmapAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.DEFAULT);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mToaDiaChanBitmapAtlas, this, "skill_toa_dia_chan.png", 0, 0);
		mEngine.getTextureManager().loadTexture(mToaDiaChanBitmapAtlas);

		mToaDiaChanChildTexture = new TiledTextureRegion(
				mToaDiaChanBitmapAtlas, 920, 0, 104, 460, 2, 1);
		mToaDiaChanTextureRegion = new TiledTextureRegion(
				mToaDiaChanBitmapAtlas, 0, 0, 920, 512, 4, 2);
	}

	// private void unLoadToaDiaChan() {
	// for (int i = 0; i < mISkillUse.size(); i++) {
	// AnimatedSkill pISkill = mISkillUse.get(i);
	//
	// if (pISkill instanceof SkillToaDiaChan) {
	// AnimatedSprite child;
	// TiledTextureRegion textureChild;
	// TiledTextureRegion texture;
	//
	// pISkill = (SkillToaDiaChan) (pISkill);
	// child = (AnimatedSprite) pISkill.getChild(0);
	// textureChild = child.getTextureRegion();
	// texture = pISkill.getTextureRegion();
	//
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// pISkill.getVertexBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// pISkill.getVertexBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// texture.getTextureBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// textureChild.getTextureBuffer());
	// }
	//
	// }
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mToaDiaChanChildTexture.getTextureBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mToaDiaChanTextureRegion.getTextureBuffer());
	// mEngine.getTextureManager().unloadTexture(mToaDiaChanBitmapAtlas);
	// }
	//
	// private void unLoadBangHaMoc() {
	// for (int i = 0; i < mISkillUse.size(); i++) {
	// AnimatedSkill pISkill = mISkillUse.get(i);
	//
	// if (pISkill instanceof SkillBangHa
	// || pISkill instanceof SkillDaiMocTran) {
	// TiledTextureRegion texture = pISkill.getTextureRegion();
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// pISkill.getVertexBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// texture.getTextureBuffer());
	// }
	// }
	//
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mBangHaTextureRegion.getTextureBuffer());
	// mEngine.getTextureManager().unloadTexture(mBangHaMocBitmapAtlas);
	// }

	private void onLoadIconSkill() {
		mIconSkillListTextureRegion = new TextureRegion[totalSkill];
		int count = 0;

		while (count < totalSkill) {
			int k = count / 5;
			int i = count % 5;

			mIconSkillListTextureRegion[count] = new TextureRegion(
					mMeleeRangeTextureAtlas, 581 + i * 88, k * 102, 87, 102);
			count++;
		}

		mBrightIconSkillTextureRegion = new TextureRegion(
				mMeleeRangeTextureAtlas, 909, 287, 115, 115);
		mMaskIconSkillTextureRegion = new TextureRegion(
				mMeleeRangeTextureAtlas, 872, 211, 74, 74);
		mPlusIconSkillTextureRegion = new TextureRegion(
				mMeleeRangeTextureAtlas, 945, 211, 74, 74);
	}

	private void loadCrossBowArrow() {
		this.mArrowsTRegion = new TextureRegion[5];
		this.mCrossBowTRegion = new TextureRegion[5];
		mSkillPassiveTextureRegion = new TextureRegion[3];

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mEquipBitmapAtlas, this, "crossbow_array_list.png", 0, 0);

		mSkillPassiveTextureRegion[2] = new TextureRegion(mEquipBitmapAtlas,
				320, 209, 180, 20);
		mSkillPassiveTextureRegion[1] = new TextureRegion(mEquipBitmapAtlas,
				135, 209, 180, 20);
		mSkillPassiveTextureRegion[0] = new TextureRegion(mEquipBitmapAtlas,
				320, 230, 180, 20);

		mArrowsTRegion[1] = new TextureRegion(mEquipBitmapAtlas, 0, 169, 128,
				16);
		mArrowsTRegion[4] = new TextureRegion(mEquipBitmapAtlas, 128, 169, 128,
				16);
		mArrowsTRegion[3] = new TextureRegion(mEquipBitmapAtlas, 256, 169, 128,
				16);
		mArrowsTRegion[2] = new TextureRegion(mEquipBitmapAtlas, 384, 169, 128,
				16);
		mArrowsTRegion[0] = new TextureRegion(mEquipBitmapAtlas, 256, 185, 128,
				16);

		mCrossBowTRegion[0] = new TextureRegion(mEquipBitmapAtlas, 0, 0, 100,
				170);
		mCrossBowTRegion[1] = new TextureRegion(mEquipBitmapAtlas, 100, 0, 100,
				170);
		mCrossBowTRegion[2] = new TextureRegion(mEquipBitmapAtlas, 200, 0, 100,
				170);
		mCrossBowTRegion[3] = new TextureRegion(mEquipBitmapAtlas, 300, 0, 100,
				170);
		mCrossBowTRegion[4] = new TextureRegion(mEquipBitmapAtlas, 400, 0, 112,
				170);

	}

	// private void onLoadResourceSkill(int... pId) {
	// int size = pId.length;
	// for (int i = 0; i < size; i++) {
	// switch (pId[i]) {
	// case Constants.SKILL_LIEU_NGUYEN_HOA:
	// mEngine.getTextureManager().loadTexture(
	// mLieuNguyenHoaBitmapAtlas);
	// break;
	// case Constants.SKILL_LOI_QUANG_DIEN:
	// mEngine.getTextureManager().loadTexture(
	// mLoiQuangDienBitmapAtlas);
	// break;
	// case Constants.SKILL_BANG_HA:
	// if (!mBangHaMocBitmapAtlas.isLoadedToHardware())
	// mEngine.getTextureManager().loadTexture(
	// mBangHaMocBitmapAtlas);
	// break;
	// case Constants.SKILL_DAI_MOC_TRAN:
	// if (!mBangHaMocBitmapAtlas.isLoadedToHardware())
	// mEngine.getTextureManager().loadTexture(
	// mBangHaMocBitmapAtlas);
	// break;
	// case Constants.SKILL_TOA_DIA_CHAN:
	// mEngine.getTextureManager().loadTexture(mToaDiaChanBitmapAtlas);
	// break;
	//
	// default:
	// break;
	// }
	// }
	// }
	//
	// private void unLoadResourcesSkill(int id) {
	// switch (id) {
	// case Constants.SKILL_LIEU_NGUYEN_HOA:
	// unLoadLieuNguyenHoa();
	// break;
	// case Constants.SKILL_LOI_QUANG_DIEN:
	// unLoadLoiQuangDien();
	// break;
	// case Constants.SKILL_BANG_HA:
	// unLoadBangHaMoc();
	// break;
	// case Constants.SKILL_DAI_MOC_TRAN:
	// unLoadBangHaMoc();
	// break;
	// case Constants.SKILL_TOA_DIA_CHAN:
	// unLoadToaDiaChan();
	// break;
	// default:
	// break;
	// }
	// }

	private void callSkill(int idSkill, final float pX, final float pY) {
		if (idSkill == -1)
			return;
		switch (idSkill) {
		case 9:
			callToaDiaChan(pX, pY, mSkillButton[button].getDamage(),
					mSkillButton[button].getLevel());
			break;
		case 1:
			callLieuNguyenHoa(pX, pY, mSkillButton[button].getDamage());
			break;
		case 5:
			callDaiMocTran(pX, pY, mSkillButton[button].getDamage());

			break;
		case 7:
			callLoiQuangDien(pX, pY, mSkillButton[button].getDamage());
			break;
		case 3:
			callBangHa(pX, pY, mSkillButton[button].getDamage(),
					mSkillButton[button].getDelayEnemy());
			break;
		default:
			break;
		}
		try {
			mSkillButton[button].used();
			mGeneral.reducedMana(mSkillButton[button].getUseMana());
			button = -1;

		} catch (Exception e) {
		}
	}

	private void callToaDiaChan(final float pX, final float pY, float damage,
			final int level) {
		final SkillToaDiaChan toaDiaChan = new SkillToaDiaChan(
				Constants.SKILL_TOA_DIA_CHAN, pX, pY,
				mToaDiaChanTextureRegion.deepCopy(),
				mToaDiaChanChildTexture.deepCopy());
		toaDiaChan.setDamage(damage);
		toaDiaChan.setLevel(level);

		mISkillUse.add(toaDiaChan);
		mMainScene.attachChildToHighest(toaDiaChan);

		if (isMainGameScene && !isPause) {
			try {
				sEarthquake.play();
			} catch (Exception e) {
			}
		}
		MainGame.this.mCamera.setShake(true);
	}

	private void callDaiMocTran(final float pX, final float pY, float damage) {
		final SkillDaiMocTran daiMocTran = new SkillDaiMocTran(
				Constants.SKILL_DAI_MOC_TRAN, pX, pY,
				mDaiMocTranTextureRegion.deepCopy());

		daiMocTran.setDamage(damage);
		daiMocTran.setZIndex(1);

		mISkillUse.add(daiMocTran);
		mMainScene.attachChild(daiMocTran);
		mMainScene.sortChildren();

		if (isMainGameScene && !isPause) {
			try {
				sSkillTree.play();
				mCamera.setShake(true);
			} catch (Exception e) {
			}
		}
	}

	private void callBangHa(final float pX, final float pY, float damage,
			long delayEnemy) {
		final SkillBangHa ice = new SkillBangHa(Constants.SKILL_BANG_HA, pX,
				pY, mBangHaTextureRegion);

		ice.setDamage(damage);
		ice.setCoolDownEnemy(delayEnemy);

		mISkillUse.add(ice);
		mMainScene.attachChildToHighest(ice);

		if (isMainGameScene && !isPause) {
			try {
				sIceSkill.play();
			} catch (Exception e) {
			}
		}

	}

	private void callLoiQuangDien(final float pX, final float pY, float damage) {
		final SkillLoiQuangDien light = new SkillLoiQuangDien(
				Constants.SKILL_LOI_QUANG_DIEN, pX, pY,
				mLoiQuangDienTextureRegion.deepCopy());

		light.setDamage(damage);

		mISkillUse.add(light);
		mMainScene.attachChildToHighest(light);

		if (isMainGameScene && !isPause) {
			try {
				sLightSkill.play();
			} catch (Exception e) {
			}
			MainGame.this.mCamera.setShake(true);
		}

	}

	private void callLieuNguyenHoa(final float pX, final float pY, float damage) {
		final SkillLieuNguyenHoa fireSkill = new SkillLieuNguyenHoa(
				Constants.SKILL_LIEU_NGUYEN_HOA, pX, pY,
				mLieuNguyenHoaTextureRegion.deepCopy());
		fireSkill.setDamage(damage);

		mISkillUse.add(fireSkill);
		mMainScene.attachChildToHighest(fireSkill);

		MoveModifier modifirer = new MoveModifier(0.25f, fireSkill.getX(),
				pX - 110, fireSkill.getY(), pY - 110);
		modifirer.setRemoveWhenFinished(true);
		fireSkill.registerEntityModifier(modifirer.deepCopy());

		if (isMainGameScene && !isPause) {
			try {
				sFireSkill.play();
				mCamera.setShake(true);
			} catch (Exception e) {
			}
		}

	}

	// ============== //
	// MinisterEnemy //
	// ============== //

	private void onLoadResourcesNhamNgao() {
		mNhamNgaoBitmapAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.NEAREST_PREMULTIPLYALPHA);
		mNhamNgaoBitmapAttackAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mNhamNgaoBitmapAttackAtlas, this, "enemy_nhamngao_attack.png",
				0, 0);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mNhamNgaoBitmapAtlas, this, "enemy_nhamngao.png", 0, 0);

		// mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
		// mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);

		mNhamNgaoMove = new TiledTextureRegion(mNhamNgaoBitmapAtlas, 0, 0,
				1022, 420, 7, 3);
		mNhamNgaoAttack = new TiledTextureRegion(mNhamNgaoBitmapAttackAtlas, 0,
				0, 880, 380, 4, 2);
	}

	private void onLoadResourcesDoThu() {
		mDoThuBitmapTextureAtlas = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mDoThuBitmapTextureAtlas, this, "enemy_dothu.png", 0, 0);

		mDoThuTextureRegion = new TiledTextureRegion(mDoThuBitmapTextureAtlas,
				0, 0, 840, 510, 6, 3);

		mDoThuSkillTextureRegion = new TextureRegion(mDoThuBitmapTextureAtlas,
				840, 0, 25, 90);

	}

	// private void onLoadResourcesTanNhiThe() {
	// mTanNhiTheBitmapTextureAtlas = new BitmapTextureAtlas(512, 512,
	// TextureOptions.BILINEAR);
	//
	// BitmapTextureAtlasTextureRegionFactory
	// .createFromAsset(mTanNhiTheBitmapTextureAtlas, this,
	// "enemy_tannhithe.png", 0, 0);
	//
	// mTanNhiTheTextureRegion = new TiledTextureRegion(
	// mTanNhiTheBitmapTextureAtlas, 0, 0, 510, 488, 5, 4);
	// mArrowOfTanNhiThe = new TextureRegion(mTanNhiTheBitmapTextureAtlas, 0,
	// 500, 80, 12);
	//
	// mEngine.getTextureManager().loadTexture(mTanNhiTheBitmapTextureAtlas);
	// }

	// private void unLoadResourcesDragon() {
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// flatDragon.getVertexBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mFlatDragonMoveTextureRegion.getTextureBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mFlatDragonAttackTextureRegion.getTextureBuffer());
	// mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
	// mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
	//
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// flyingDragon.getVertexBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mFlyingDragonDieTextureRegion.getTextureBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mFlyingDragonFireTextureRegion.getTextureBuffer());
	// BufferObjectManager.getActiveInstance().unloadBufferObject(
	// mFlyingDragonMoveTextureRegion.getTextureBuffer());
	// mEngine.getTextureManager().unloadTexture(mFlyingDragonBitmapAttackDie);
	// mEngine.getTextureManager().unloadTexture(mFlyingDragonBitmapMove);
	// }

	private void onLoadResourcesFlatDragon() {
		mFlatDragonBitmapAttack = new BitmapTextureAtlas(512, 1024,
				TextureOptions.BILINEAR);
		mFlatDragonBitmapMove = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR);
		mSkillFireDragonBitmap = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mFlatDragonBitmapAttack, this, "enemy_flatdragon_attack.png",
				0, 0);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mFlatDragonBitmapMove, this, "enemy_flatdragon_move.png", 0, 0);
		mSkillFireDragonTextureRegon = BitmapTextureAtlasTextureRegionFactory
				.createTiledFromAsset(mSkillFireDragonBitmap, this,
						"enemy_dragon_fire_skill.png", 0, 0, 1, 4);

		// mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
		// mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
		// mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);

		mFlatDragonAttackTextureRegion = new TiledTextureRegion(
				mFlatDragonBitmapAttack, 0, 0, 512, 950, 4, 5);
		mFlatDragonMoveTextureRegion = new TiledTextureRegion(
				mFlatDragonBitmapMove, 0, 0, 500, 380, 5, 2);
	}

	// private void onLoadResourcesFlyingDragon() {
	// mFlyingDragonBitmapAttackDie = new BitmapTextureAtlas(1024, 1024,
	// TextureOptions.BILINEAR);
	// mFlyingDragonBitmapMove = new BitmapTextureAtlas(1024, 1024,
	// TextureOptions.BILINEAR);
	// mBeatBitmap = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR);
	//
	// BitmapTextureAtlasTextureRegionFactory.createFromAsset(
	// mFlyingDragonBitmapMove, this, "enemy_flyingdragon_fly.png", 0,
	// 0);
	// BitmapTextureAtlasTextureRegionFactory.createFromAsset(
	// mFlyingDragonBitmapAttackDie, this,
	// "enemy_flyingdragon_die.png", 0, 0);
	// BitmapTextureAtlasTextureRegionFactory.createFromAsset(mBeatBitmap,
	// this, "enemy_beat_dragon.png", 0, 0);
	//
	// mFlyingDragonFireTextureRegion = new TiledTextureRegion(
	// mFlyingDragonBitmapAttackDie, 0, 334, 920, 690, 4, 2);
	// mFlyingDragonDieTextureRegion = new TiledTextureRegion(
	// mFlyingDragonBitmapAttackDie, 0, 0, 920, 334, 4, 1);
	// mFlyingDragonMoveTextureRegion = new TiledTextureRegion(
	// mFlyingDragonBitmapMove, 0, 0, 920, 1023, 4, 3);
	//
	// mEngine.getTextureManager().loadTexture(mFlyingDragonBitmapAttackDie);
	// mEngine.getTextureManager().loadTexture(mFlyingDragonBitmapMove);
	//
	// mEngine.getTextureManager().loadTexture(mBeatBitmap);
	//
	// }

	private void onLoadResourcesEquipment() {
		mBackgroundBitmap = new BitmapTextureAtlas(1024, 512,
				TextureOptions.NEAREST_PREMULTIPLYALPHA);
		mGeneralBitmap = new BitmapTextureAtlas(1024, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mListSkillBitmap = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mListItemBitmap = new BitmapTextureAtlas(512, 512,
				TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mEquipmentOtherBitmap = new BitmapTextureAtlas(1024, 512,
				TextureOptions.NEAREST);
		mEquipmentRemoveSkillBitmap = new BitmapTextureAtlas(1024, 512,
				TextureOptions.DEFAULT);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mEquipmentRemoveSkillBitmap, this, "removeskill.png", 0, 0);

		mContainTaytuykinhTextureRegion = new TextureRegion(
				mEquipmentRemoveSkillBitmap, 0, 0, 394, 322);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mEquipmentOtherBitmap, this, "equipment_other.png", 0, 0);

		mRemovableTextureRegion = new TextureRegion(mEquipmentOtherBitmap, 1,
				335, 31, 31);
		mRemovable_select_TextureRegion = new TextureRegion(
				mEquipmentOtherBitmap, 35, 332, 42, 34);

		mBoardInfo = new TextureRegion(mEquipmentRemoveSkillBitmap, 393, 0,
				498, 365);
		mBoardInfoSmall = new TextureRegion(mEquipmentOtherBitmap, 520, 0, 280,
				174);

		mPlusTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				89, 329, 80, 40, 2, 1);

		mReturnTiledTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 512, 269, 178, 33, 2, 1);
		mSaleTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 407, 178, 33, 2, 1);
		mYesTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 478, 178, 33, 2, 1);
		mNoTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 303, 178, 33, 2, 1);
		mUpgradeTiledTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 512, 372, 178, 33, 2, 1);
		mBuyTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 444, 178, 33, 2, 1);
		mPayTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 182, 222, 42, 2, 1);
		mUseTiledTextureRegion = new TiledTextureRegion(mEquipmentOtherBitmap,
				512, 338, 178, 33, 2, 1);
		mBigReturnTiledTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 0, 280, 224, 43, 2, 1);
		mPlayTextureRegionE = new TiledTextureRegion(mEquipmentOtherBitmap,
				108, 190, 124, 88, 1, 2);
		mDetailTiledTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 512, 235, 178, 33, 2, 1);

		mTaytuykinhTextureRegion = new TextureRegion(mEquipmentOtherBitmap, 0,
				190, 64, 64);

		// mCoolDownTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 700,
		// 470, 45, 40);
		// mUpAttackTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 745,
		// 390, 45, 40);
		// mUpDefendTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 745,
		// 430, 45, 40);
		// mUpStrengTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 745,
		// 350, 45, 40);
		// mUpArrowTextureRegion = new TextureRegion(mEquipmentOtherBitmap, 745,
		// 310, 45, 40);
		// mUpArrowVelocityTextureRegion = new TextureRegion(
		// mEquipmentOtherBitmap, 700, 430, 45, 40);
		// mBounderyTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 700,
		// 310, 45, 40);
		// mSnailPriceTextureRegion = new TextureRegion(mEquipmentOtherBitmap,
		// 700, 390, 45, 40);
		// mUpIntelTextureRegion = new TextureRegion(mEquipmentOtherBitmap, 700,
		// 350, 45, 40);

		mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory
				.createFromAsset(mBackgroundBitmap, this,
						"background_equipment.png", 0, 0);
		mBackgroundSpliteGeneralTextureRegion = new TextureRegion(
				mEquipmentOtherBitmap, 237, 0, 274, 420);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				mListSkillBitmap, this, "skill_list.png", 0, 0);
		BitmapTextureAtlasTextureRegionFactory.createFromAsset(mListItemBitmap,
				this, "item_list.png", 0, 0);

		BitmapTextureAtlasTextureRegionFactory.createFromAsset(mGeneralBitmap,
				this, "general_list.png", 0, 0);
		mAnDuongVuongTextureRegion = new TextureRegion(mGeneralBitmap, 0, 0,
				275, 350);
		mDichHuTongTextureRegion = new TextureRegion(mGeneralBitmap, 275, 0,
				275, 350);
		mCaoLoTextureRegion = new TextureRegion(mGeneralBitmap, 550, 0, 275,
				350);

		mSkillSelectTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 0, 95, 210, 90, 1, 2);
		mItemSelectTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 0, 0, 210, 90, 1, 2);

		mUnLockMenu = new TextureRegion(mListItemBitmap, 0, 128, 70, 70);
		mLockMenu = new TextureRegion(mListItemBitmap, 384, 64, 70, 70);
		mContainMenu = new TextureRegion(mListSkillBitmap, 130, 130, 76, 76);

		mContainGoldTextureRegion = new TiledTextureRegion(
				mEquipmentOtherBitmap, 0, 457, 460, 65, 2, 1);

		mScrollTextureRegion = new TextureRegion(mEquipmentOtherBitmap, 0, 395,
				40, 55);

		mListSkillTextureRegions = new TextureRegion[10];
		mListSkillMenu = new SkillMenu[Constants.TOTAL_SKILL];
		mListItemTextureRegions = new TextureRegion[Constants.TOTAL_ITEM];
		mListItemMenu = new ItemMenu[Constants.TOTAL_ITEM];
		mContainSkillList = new MySprite[Constants.TOTAL_SKILL];
		mContainItemList = new MySprite[Constants.TOTAL_ITEM];
		mListLockItemList = new MySprite[Constants.TOTAL_ITEM];
		mListLockSkillList = new MySprite[Constants.TOTAL_SKILL];

		ID_Skill_Use = new int[3];
		ID_Item_Use = new int[4];

		ID_Skill_Store = new int[totalSkill];

		int countE = 0;

		while (countE < totalItem) {
			int k = countE / 8;
			int p = countE % 8;

			mListItemTextureRegions[countE] = new TextureRegion(
					mListItemBitmap, +p * 64, k * 64, 64, 64);
			countE++;

		}

		countE = 0;
		while (countE < totalSkill) {
			int k = countE / 4;
			int p = countE % 4;

			mListSkillTextureRegions[countE] = new TextureRegion(
					mListSkillBitmap, +p * 64, k * 64, 64, 64);

			countE++;
		}

		mEngine.getTextureManager().loadTexture(mBackgroundBitmap);
		mEngine.getTextureManager().loadTexture(mEquipmentOtherBitmap);
		mEngine.getTextureManager().loadTexture(mGeneralBitmap);
		mEngine.getTextureManager().loadTexture(mListSkillBitmap);
		mEngine.getTextureManager().loadTexture(mListItemBitmap);
		mEngine.getTextureManager().loadTexture(mEquipmentRemoveSkillBitmap);
	}

	private boolean isTouchDown = false;

	private void onLoadResourcesAccount() {

		mContainAccountTextureRegion = new TextureRegion(mAccountBitmap1, 0, 0,
				253, 365);
		mContainAccountResetTextureRegion = new TextureRegion(mAccountBitmap1,
				523, 298, 253, 54);
		mGeneralIcon = new TextureRegion[3];
		mAnDuongVuong_IconTextureRegion = new TextureRegion(mAccountBitmap1, 0,
				373, 154, 139);
		mDichHuTong_IconTextureRegion = new TextureRegion(mAccountBitmap1, 155,
				373, 154, 139);
		mCaoLo_IconTextureRegion = new TextureRegion(mAccountBitmap1, 309, 373,
				154, 139);

		mGeneralIcon[0] = mDichHuTong_IconTextureRegion;
		mGeneralIcon[1] = mCaoLo_IconTextureRegion;
		mGeneralIcon[2] = mAnDuongVuong_IconTextureRegion;

		mSnailCoinIcon = new TextureRegion(mAccountBitmap1, 845, 472, 47, 37);

	}

	public boolean onSceneTouchEvent(Scene arg0, TouchEvent pSceneTouch) {
		switch (mGameStates) {
		case GAME_PLAY:
			switch (pSceneTouch.getAction()) {
			case TouchEvent.ACTION_DOWN:
				if (isLockMainScene) {
					isLockMainScene = false;
					return true;
				}
				xTouch = pSceneTouch.getX();
				yTouch = pSceneTouch.getY();
				if (pause_button.contains(xTouch, yTouch)) {
					if (!isPause) {
						isPause = true;
						pauseGame();
						return true;
					}

				}
				if (xTouch > 120) {
					if ((this.xTouch >= mSkillButton[2].getX())
							&& (this.yTouch >= mSkillButton[2].getY())) {
						for (int i = 0; i < 3; i++) {
							if (mSkillButton[i].checkUsable(xTouch, yTouch)
									&& mGeneral.getManaPoints() > mSkillButton[i]
											.getUseMana()) {
								isSkill = true;
								idSkilllUse = mSkillButton[i].getIdSkill();
								button = i;
								if (mSkillButton[i].getState() == StateSkill.ACTIVE) {
									magic_circle.setPosition(
											this.xTouch
													- magic_circle.getWidth()
													/ 2.0f,
											this.yTouch
													- magic_circle.getHeight()
													/ 2.0f);
									magic_circle.setVisible(true);
								}
								break;
							}
							isTouch = false;
							isFire = false;
						}
					} else {
						isTouch = true;
						isFire = true;
					}
				} else {
					isFire = false;
					isSkill = false;
					isTouch = true;
				}

				return true;
			case TouchEvent.ACTION_MOVE:
				xTouch = pSceneTouch.getX();
				yTouch = pSceneTouch.getY();

				if (xTouch > 120) {
					if (isSkill) {
						if (idSkilllUse % 2 == 1) {
							magic_circle.setPosition(
									this.xTouch - magic_circle.getWidth()
											/ 2.0f,
									this.yTouch - magic_circle.getHeight()
											/ 2.0f);
						}
					} else {
						isFire = true;
						isTouch = true;
					}
				} else {
					isTouch = true;
					isFire = false;
					isSkill = false;
					magic_circle.setVisible(false);
				}

				return true;
			case TouchEvent.ACTION_UP:
				if (isSkill) {
					xSkill = pSceneTouch.getX();
					ySkill = pSceneTouch.getY();
					if (idSkilllUse % 2 == 1) {
						callSkill(idSkilllUse, xSkill, ySkill);
					}
					idSkilllUse = -1;
				}
				isTouch = false;
				isFire = false;
				isSkill = false;
				magic_circle.setVisible(false);
				return true;
			}
			break;

		case GAME_SHOP:
			xTouch = pSceneTouch.getX();
			yTouch = pSceneTouch.getY();

			if (pSceneTouch.getAction() == TouchEvent.ACTION_DOWN) {

				if (isItemMenu) {
					if (isRemoveSkill || isLockScene || isUpgradeScene
							|| isBuySnail)
						return false;
					for (int i = 0; i < 4; i++) {
						if (contain[i].contains(xTouch, yTouch)
								&& contain[i].isContainItem()) {
							isMove = true;
							mListItemMenu[contain[i].getIdItem() - totalSkill]
									.setMove(true);
							MOVE = contain[i].getIdItem();
							CONTAIN_MOVE = i;
							return false;
						}
					}
				} else {
					if (isRemoveSkill || isLockScene || isUpgradeScene
							|| isBuySnail)
						return false;
					if (contain[0].contains(xTouch, yTouch)) {
						sButtonClicked.play();
						selectRemoveSkill = true;
						isRemoveSkill = true;
						return false;
					} else {
						for (int i = 1; i < 4; i++) {
							if (contain[i].contains(xTouch, yTouch)
									&& contain[i].isContainSkill()) {
								sButtonClicked.play();
								isMove = true;
								MOVE = contain[i].getIdSkill();
								CONTAIN_MOVE = i;
								return false;
							}
						}
					}
				}
			} else if (pSceneTouch.getAction() == TouchEvent.ACTION_MOVE) {
				if (isMove) {
					if (isItemMenu) {
						if (!contain[CONTAIN_MOVE].contains(xTouch, yTouch))
							mListItemMenu[MOVE - totalSkill].setPosition(
									xTouch - 40, yTouch - 40);
					} else {
						selectRemoveSkill = false;
					}
				} else if (isAcceptMoveItem) {
					mListItemMenu[itemMoveable].setPosition(xTouch - 80,
							yTouch - 80);
				}

			} else if (pSceneTouch.getAction() == TouchEvent.ACTION_UP) {
				if (selectRemoveSkill) {
					showRemove();
					return false;
				}

				if (isMove) {
					if (contain_select.contains(xTouch, yTouch)) {
						if (isItemMenu) {
							contain[CONTAIN_MOVE].setContainItem(false);
							contain[CONTAIN_MOVE].setIdItem(-1);
							contain[CONTAIN_MOVE].setKindOfEquipmentItem(-1);
							ItemMenu item_menu = mListItemMenu[MOVE
									- totalSkill];
							item_menu.setPosition(item_menu.xPos,
									item_menu.yPos);
							item_menu.setpX(item_menu.xPos);
							item_menu.setpY(item_menu.yPos);

							item_menu.setZIndex(1);

							gameStore.removeItemUsed(CONTAIN_MOVE);
						}

					} else if (contain[CONTAIN_MOVE].contains(xTouch, yTouch)) {
						if (isItemMenu) {
							sButtonClicked.play();
							itemClicked = mListItemMenu[MOVE - totalSkill];
							itemClicked.setPosition(
									contain[CONTAIN_MOVE].getX() + 5,
									contain[CONTAIN_MOVE].getY() + 5);
							buy.setVisible(false);
							use.setVisible(false);
							sale.setVisible(true);
							showInforItem(itemClicked);
						} else {
							buy.setVisible(false);
							use.setVisible(false);
							up.setVisible(true);
							skillClicked = mListSkillMenu[MOVE];
							showInfoSkill(skillClicked);
						}
					} else {
						if (isItemMenu) {
							ItemMenu item_menu = mListItemMenu[MOVE
									- totalSkill];
							item_menu.setPosition(item_menu.getpX(),
									item_menu.getpY());
						}
					}

					isMove = false;
					MOVE = -1;
					CONTAIN_MOVE = -1;
				} else if (isAcceptMoveItem) {
					for (int i = 0; i < 4; i++) {
						ItemMenu item = mListItemMenu[itemMoveable];
						if (contain[i].contains(xTouch, yTouch) || contain[i].collidesWith(item)) {

							for (int j = 0; j < 4; j++) {
								if (contain[j].getKindOfEquipmentItem() == item.kindOfEquipment) {

									ItemMenu item_menu = mListItemMenu[contain[j]
											.getIdItem() - totalSkill];
									item_menu.setPosition(item_menu.xPos,
											item_menu.yPos);
									item_menu.setpX(item_menu.xPos);
									item_menu.setpY(item_menu.yPos);
									item_menu.setContainBy(-1);

									item_menu.setZIndex(1);

									contain[j].setContainItem(false);
									contain[j].setIdItem(-1);
									contain[j].setKindOfEquipmentItem(-1);

									gameStore.removeItemUsed(j);

									item.setScale(1);
									item.setContainBy(j);
									item.setpX(contain[j].getX() + 5);
									item.setpY(contain[j].getY() + 5);
									item.setZIndex(5);
									mEquipmentScene.sortChildren();
									item.setPosition(contain[j].getX() + 5,
											contain[j].getY() + 5);

									contain[j]
											.setKindOfEquipmentItem(item.kindOfEquipment);
									contain[j].setContainItem(true);
									contain[j].setIdItem(item.getID());

									gameStore.useItem(j, item.getID());
									gameStore.newItem(item.getID());

									isUsedMove = true;
									break;
								}
							}
							
//							if (isUsedMove) {
//								itemMoveable = -1;
//								isMoveItemToUse = false;
//								isAcceptMoveItem = false;
//								isUsedMove = false;
//								break;
//							}
							
							if (!isUsedMove) {
								if (contain[i].isContainItem()) {
									ItemMenu item_menu = mListItemMenu[contain[i]
											.getIdItem() - totalSkill];
									item_menu.setPosition(item_menu.xPos,
											item_menu.yPos);
									item_menu.setpX(item_menu.xPos);
									item_menu.setpY(item_menu.yPos);
									item_menu.setContainBy(-1);

									item_menu.setZIndex(1);

									contain[i].setContainItem(false);
									contain[i].setIdItem(-1);
									contain[i].setKindOfEquipmentItem(-1);

									gameStore.removeItemUsed(i);

									item.setScale(1);
									item.setContainBy(i);
									item.setpX(contain[i].getX() + 5);
									item.setpY(contain[i].getY() + 5);
									item.setZIndex(5);
									mEquipmentScene.sortChildren();
									item.setPosition(contain[i].getX() + 5,
											contain[i].getY() + 5);

									contain[i]
											.setKindOfEquipmentItem(item.kindOfEquipment);
									contain[i].setContainItem(true);
									contain[i].setIdItem(item.getID());

									gameStore.useItem(i, item.getID());
									gameStore.newItem(item.getID());

									isUsedMove = true;
									break;
								} else {
									item.setScale(1);
									item.setContainBy(i);
									item.setpX(contain[i].getX() + 5);
									item.setpY(contain[i].getY() + 5);
									item.setZIndex(5);
									mEquipmentScene.sortChildren();
									item.setPosition(contain[i].getX() + 5,
											contain[i].getY() + 5);

									contain[i]
											.setKindOfEquipmentItem(item.kindOfEquipment);
									contain[i].setContainItem(true);
									contain[i].setIdItem(item.getID());

									gameStore.useItem(i, item.getID());
									gameStore.newItem(item.getID());

									isUsedMove = true;
									break;
								}
							}
						}
					}

					if (!isUsedMove) {
						ItemMenu item_menu = mListItemMenu[itemMoveable];
						item_menu.setPosition(item_menu.xPos, item_menu.yPos);
						item_menu.setScale(1);
						item_menu.setZIndex(1);
					}

					itemMoveable = -1;
					isMoveItemToUse = false;
					isAcceptMoveItem = false;
					isUsedMove = false;
				}

			}

			else {
				if (isMove) {
					if (isItemMenu) {
						// ItemMenu item_menu = mListItemMenu.get(MOVE
						// - totalSkill);
						ItemMenu item_menu = mListItemMenu[MOVE - totalSkill];
						item_menu.setPosition(item_menu.getpX(),
								item_menu.getpY());
					} else {
						// SkillMenu skill_menu = mListSkillMenu.get(MOVE);
						SkillMenu skill_menu = mListSkillMenu[MOVE];
						skill_menu.setPosition(skill_menu.getpX(),
								skill_menu.getpY());
					}
				}
				isMove = false;
			}

			if (backgroundSplite.contains(xTouch, yTouch)) {
				if (pSceneTouch.getAction() == TouchEvent.ACTION_DOWN) {
					isGeneralScroll = true;
					isScrolling = true;
					isSkillScroll = false;
					isItemScroll = false;
					isSelect = false;
				}
			} else if (contain_select.contains(xTouch, yTouch)) {

				if (pSceneTouch.getAction() == TouchEvent.ACTION_DOWN) {
					isSelect = true;
				}

				if (isItemMenu) {
					isSkillScroll = false;
					isItemScroll = true;
					if (pSceneTouch.getAction() == TouchEvent.ACTION_DOWN) {
						for (int i = 0; i < totalItem; i++) {
							ItemMenu item = mListItemMenu[i];
							if (item.contains(xTouch, yTouch)
									&& item.isUnlock()
									&& item.getLimit() <= generalStore
											.getLevel()) {
								itemMoveable = i;
								isMoveItemToUse = true;
								xTouchMoveItem = xTouch;
								yTouchMoveItem = yTouch;
								break;
							}
						}
					}

					isGeneralScroll = false;
				} else {
					isSkillScroll = true;
					isItemScroll = false;
					isMoveItemToUse = false;

					isGeneralScroll = false;
				}

			} else {
				isSelect = false;
				isSkillScroll = false;
				isItemScroll = false;
				isGeneralScroll = false;
				isMoveItemToUse = false;
			}

			this.mClickDetector.onTouchEvent(pSceneTouch);
			this.mScrollDetector.onTouchEvent(pSceneTouch);

			break;

		case GAME_OVER:
			switch (pSceneTouch.getAction()) {
			case TouchEvent.ACTION_DOWN:
				if (!isHold)
					isTouchDown = true;
				break;

			case TouchEvent.ACTION_UP:
				if (isTouchDown) {
					try {
						sTransitionScene.play();
					} catch (Exception e) {
					}

					isTouchDown = false;
					mEngine.start();
					detackMainGameScene();
					setEquipmentScene();
					System.gc();
				}

				break;
			default:
				break;
			}
			break;

		case GAME_WIN:
			switch (pSceneTouch.getAction()) {
			case TouchEvent.ACTION_DOWN:
				if (!isHold)
					isTouchDown = true;
				break;

			case TouchEvent.ACTION_UP:
				if (isTouchDown) {
					isTouchDown = false;
					try {
						sTransitionScene.play();
					} catch (Exception e) {
					}
					mEngine.start();
					detackMainGameScene();

					if (lastGameStage == 99) {
						onLoadEndOfStart();
						onShowEndOfStart();
					} else {
						setEquipmentScene();
						System.gc();
					}
				}

				break;
			default:
				break;
			}
			break;

		case GAME_END_OF_START:
			switch (pSceneTouch.getAction()) {
			case TouchEvent.ACTION_DOWN:
				if (!isEndOfStart) {
					isTouchDown = true;
				}
				break;

			case TouchEvent.ACTION_UP:
				if (isTouchDown) {
					try {
						sTransitionScene.play();
					} catch (Exception e) {
					}
					isTouchDown = false;
					onUnshowEndOfStart();
					setEquipmentScene();
					System.gc();
				}
				break;

			default:
				break;
			}
			break;

		case GAME_PAUSE:
			xTouch = pSceneTouch.getX();
			yTouch = pSceneTouch.getY();
			if (pSceneTouch.getAction() == TouchEvent.ACTION_DOWN)
				if (continueSprite.contains(xTouch, yTouch)) {
					mMainScene.clearChildScene();
					mGameStates = GameStates.GAME_PLAY;
					resumeCallEnemy = System.currentTimeMillis();
					totalPauseGame += resumeCallEnemy - pauseCallEnemy;
					mEngine.start();
					try {
						mBackgroundMusic.resume();
					} catch (Exception e) {
					}
					isPause = false;
				} else if (exitSprite.contains(xTouch, yTouch)) {
					mMainScene.clearChildScene();
					detackMainGameScene();
					finish();
					System.gc();
				} else if (replaySprite.contains(xTouch, yTouch)) {
					try {
						sTransitionScene.play();
					} catch (Exception e) {
					}
					detackMainGameScene();
					setEquipmentScene();
					System.gc();
				}

			break;

		default:
			break;
		}

		return true;
	}

	private void onLoadGameAccountStore() {
		gameStore = mGameSrotes[ACCOUNT];
		generalUse = generalLastUsed[ACCOUNT];
		generalStore = gameStore.getGeneral(generalUse);

		stage = this.gameStore.getStage();
//		stage = 20;

		if (stage > Constants.STAGE_BOSS_4)
			stage = Constants.STAGE_BOSS_4;

		if (callMinisterEnemy == null)
			callMinisterEnemy = new int[3];
		for (int i = 0; i < 3; i++) {
			callMinisterEnemy[i] = -1;
		}

		switch (stage) {
		case Constants.STAGE_BOSS_NHAMNGAO_1:
			callMinisterEnemy[0] = 0;

			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);

			break;
		case Constants.STAGE_BOSS_NHAMNGAO_2:
			callMinisterEnemy[0] = 0;

			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);

			break;
		case Constants.STAGE_BOSS_DOTHU_1:
			callMinisterEnemy[1] = 1;

			mEngine.getTextureManager().loadTexture(mDoThuBitmapTextureAtlas);
			break;
		case Constants.STAGE_BOSS_DOTHU_2:
			callMinisterEnemy[1] = 1;

			mEngine.getTextureManager().loadTexture(mDoThuBitmapTextureAtlas);
			break;
		case Constants.STAGE_BOSS_FLAT_DRAGON_1:
			callMinisterEnemy[2] = 2;

			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);
			break;
		case Constants.STAGE_BOSS_FLAT_DRAGON_2:
			callMinisterEnemy[2] = 2;

			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);
			break;
		case Constants.STAGE_BOSS_1:
			callMinisterEnemy[0] = 0;
			callMinisterEnemy[1] = 1;

			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);

			mEngine.getTextureManager().loadTexture(mDoThuBitmapTextureAtlas);
			break;
		case Constants.STAGE_BOSS_2:
			callMinisterEnemy[1] = 1;
			callMinisterEnemy[2] = 2;

			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);

			mEngine.getTextureManager().loadTexture(mDoThuBitmapTextureAtlas);
			break;

		case Constants.STAGE_BOSS_3:
			callMinisterEnemy[0] = 0;
			callMinisterEnemy[2] = 2;

			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);

			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);
			break;
		case Constants.STAGE_BOSS_4:
			callMinisterEnemy[1] = 1;
			callMinisterEnemy[2] = 2;
			callMinisterEnemy[0] = 0;

			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().loadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().loadTexture(mSkillFireDragonBitmap);

			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().loadTexture(mNhamNgaoBitmapAttackAtlas);

			mEngine.getTextureManager().loadTexture(mDoThuBitmapTextureAtlas);
			break;
		default:
			break;
		}

	}

	private float baseCoefficience;

	private void onLoadInforEnemyStage() {

		int first = stage / 20;

		float coefficience = first * 10;

		VELOCITY_X_MELEE = Constants.VELOCITY_MELEE_DEFAULT + coefficience;
		if (VELOCITY_X_MELEE > 2 * Constants.VELOCITY_MELEE_DEFAULT)
			VELOCITY_X_MELEE = 2 * Constants.VELOCITY_MELEE_DEFAULT;

		VELOCITY_X_NHAMNGAO = Constants.VELOCITY_NHAMNGAO_DEFAULT
				+ coefficience;
		if (VELOCITY_X_NHAMNGAO > 1.5f * Constants.VELOCITY_NHAMNGAO_DEFAULT)
			VELOCITY_X_NHAMNGAO = 1.5f * Constants.VELOCITY_NHAMNGAO_DEFAULT;

		VELOCITY_X_RANGE = Constants.VELOCITY_RANGE_DEFAULT + coefficience;
		if (VELOCITY_X_RANGE > 2 * Constants.VELOCITY_RANGE_DEFAULT)
			VELOCITY_X_RANGE = 2 * Constants.VELOCITY_RANGE_DEFAULT;

		VELOCITY_X_AURRA = Constants.VELOCITY_AURRA_DEFAULT + coefficience;
		if (VELOCITY_X_AURRA > 2 * Constants.VELOCITY_AURRA_DEFAULT)
			VELOCITY_X_AURRA = 2 * Constants.VELOCITY_AURRA_DEFAULT;

		VELOCITY_X_TANK = Constants.VELOCITY_TANK_DEFAULT + coefficience;
		if (VELOCITY_X_TANK > 2 * Constants.VELOCITY_TANK_DEFAULT)
			VELOCITY_X_TANK = 2 * Constants.VELOCITY_TANK_DEFAULT;

		VELOCITY_X_SPELL = Constants.VELOCITY_SPELL_DEFAULT + coefficience;
		if (VELOCITY_X_SPELL > 2 * Constants.VELOCITY_SPELL_DEFAULT)
			VELOCITY_X_SPELL = 2 * Constants.VELOCITY_SPELL_DEFAULT;

		TIMEPEREACHFRAME_ENEMY_DIE = 250;
		TIMEPEREACHFRAME_MELEE_MOVE = 80;
		TIMEPEREACHFRAME_MELEE_SPAB = 150;
		TIMEPEREACHFRAME_RANGE_FIRE = 120;
		TIMEPEREACHFRAME_RANGE_MOVE = 100;
		TIMEPEREACHFRAME_TANK_MOVE = 100;
		TIMEPEREACHFRAME_TANK_SPAB = 130;

		baseCoefficience = 1 + first * 0.25f;

		float factor = baseCoefficience * baseCoefficience;

		HP_MELEE = Constants.HP_MELEE_DEFAULT * factor;
		HP_RANGE = Constants.HP_RANGE_DEFAULT * factor;
		HP_AURRA = Constants.HP_AURRA_DEFAULT * factor;
		HP_TANK = Constants.HP_TANK_DEFAULT * factor;
		HP_SPELL = Constants.HP_SPELL_DEFAULT * factor;

		EXP_MELEE = Constants.EXP_MELEE_DEFAULT * mExpFactor;
		EXP_RANGE = Constants.EXP_RANGE_DEFAULT * mExpFactor;
		EXP_AURRA = Constants.EXP_AURRA_DEFAULT * mExpFactor;
		EXP_TANK = Constants.EXP_TANK_DEFAULT * mExpFactor;
		EXP_SPELL = Constants.EXP_SPELL_DEFAULT * mExpFactor;

		ATTACK_MELEE = Constants.ATTACK_MELEE_DEFAULT * factor;
		ATTACK_RANGE = Constants.ATTACK_RANGE_DEFAULT * factor;
		ATTACK_SPELL = Constants.ATTACK_SPELL_DEFAULT * factor;
		ATTACK_AURRA = Constants.ATTACK_AURRA_DEFAULT * factor;
		ATTACK_TANK = Constants.ATTACK_TANK_DEFAULT * factor;
	}

	private void onLoadSoundMusic() {

		try {
			sArrowGoalCityWall = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/arrow_goal_citywall.ogg");
			sDoThuSkill = SoundFactory
					.createSoundFromAsset(this.mEngine.getSoundManager(), this,
							"mfx/dothu_skill.ogg");
			sArrowGoalCityWall.setVolume(0.6f);
			sDragonFireSkill = SoundFactory
					.createSoundFromAsset(this.mEngine.getSoundManager(), this,
							"mfx/dragon_fire.ogg");
			sSkillTree = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/skill_tree.ogg");
			sSpellAttack = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/spell_attack.ogg");
			sArrowShoot = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/arrow_shot.ogg");
			sArrowGoal = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/arrow_goal.ogg");
			sSword = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/tay_dap_thanh.ogg");
			sCityWallBroken = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/fire_wall.ogg");
			sDestroyIce = SoundFactory
					.createSoundFromAsset(this.mEngine.getSoundManager(), this,
							"mfx/destroy_ice.ogg");
			sTransitionScene = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/transition_scene.ogg");
			sWallHit = SoundFactory
					.createSoundFromAsset(this.mEngine.getSoundManager(), this,
							"mfx/dragon_beat.ogg");
			sButtonClicked = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/button_click.ogg");
			sIceSkill = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/ice_skill_sound.ogg");
			sFireSkill = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/fire_skill_sound.ogg");
			sLightSkill = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this,
					"mfx/ligh_skill_sound.ogg");
			sGameOver = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/game_over.ogg");
			sWinGame = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/win.ogg");
			sEarthquake = SoundFactory.createSoundFromAsset(
					this.mEngine.getSoundManager(), this, "mfx/earthquake.ogg");
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			mBackgroundMusic = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this,
					"mfx/background_music.ogg");

			mDrum = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this, "mfx/drum.ogg");

			mSpellFlying = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this,
					"mfx/spell_flying.ogg");

			mEnemyMove = MusicFactory.createMusicFromAsset(getMusicManager(),
					this, "mfx/enemy_move.ogg");

			mMenuMusic = MusicFactory.createMusicFromAsset(
					this.mEngine.getMusicManager(), this, "mfx/menu_music.ogg");
			mDrum.setLooping(true);
			mMenuMusic.setLooping(true);
			// mDrum.setVolume(0.5f);
			mSpellFlying.setLooping(true);
			// mSpellFlying.setVolume(0.8f);
			mBackgroundMusic.setLooping(true);
			mEnemyMove.setLooping(true);
		} catch (final IOException e) {
			e.printStackTrace();
		}
		// try {
		// mGamePlayMusic = MusicFactory.createMusicFromAsset(
		// this.mEngine.getMusicManager(), this, "game_play_music.ogg");
		// } catch (IllegalStateException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }

	}

	// ==================================================================================================================
	// //
	// TOUCH
	// ===================================================================================================================
	// //

	public void onClick(ClickDetector arg0, TouchEvent pSceneTouchEvent) {
		xTouch = pSceneTouchEvent.getX();
		yTouch = pSceneTouchEvent.getY();

		if (isSelect) {
			if (isRemoveSkill) {
				return;
			}
			if (isItemMenu)
				onClickItemMenu(xTouch, yTouch);
			else
				onClickSkillMenu(xTouch, yTouch);
			isSelect = false;
		}

	}

	public void onScroll(ScrollDetector arg0, TouchEvent pSceneTouchEvent,
			final float pDistanceX, final float pDistanceY) {
		if (isInforScene)
			return;
		if (isMove)
			return;
		if (isSkillScroll) {
			scrollSkillBox(pDistanceX, pDistanceY);
			scrollLeft.setAlpha(1.0f);
			scrollRight.setAlpha(1.0f);
		} else if (isItemScroll) {
			scrollItemBox(pDistanceX, pDistanceY);
			scrollLeft.setAlpha(1.0f);
			scrollRight.setAlpha(1.0f);
		} else if (isGeneralScroll) {
			if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_UP
					|| pSceneTouchEvent.getAction() == MotionEvent.ACTION_OUTSIDE)
				scrollGeneralList(true, pDistanceX, pDistanceY);
			else
				scrollGeneralList(false, pDistanceX, pDistanceY);

		} else if (!isGeneralScroll) {
			if (isScrolling) {
				scrollGeneralList(true, pDistanceX, pDistanceY);
				isScrolling = false;
			}

		}

	}

	// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) {
		if (pEvent.getAction() == KeyEvent.ACTION_DOWN) {
			if (pKeyCode == KeyEvent.KEYCODE_BACK) {

				if (!loadFinish)
					return false;

				if (isShowShare) {
					isShowShare = false;
					isShowDialogue = false;
				}

				switch (mGameStates) {
				case GAME_PLAY:
					isPause = true;
					pauseGame();
					System.gc();

					return false;

				case GAME_PAUSE:
					return false;

				case GAME_SHOP:
					if (isInforScene) {
						if (isItemMenu)
							unShowInfoItem();
						else
							unShowInforSkill();
						return true;
					} else if (isRemoveSkill) {
						unShowRemoveSkill(false);
						return true;
					} else if (isUpgradeScene) {
						unShowUpgradeGeneral();
						return true;
					} else if (isBuySnail) {
						unShowBuySnail();
					} else if (isPopupRemoveSkill) {
						unShowPopupRemoveSkill();
					} else {
//						if (checkShowScore()) {
//							isShowDialogue = true;
////							mHighScore.setScore(calculateScore(gameStore));
////							mHighScore.sendScoreRawQuestionHandler(""+SCORE_SNAIL_DEFAULT +" ốc!");
//						} else 
						{
							try {
								sTransitionScene.play();
							} catch (Exception e) {
							}
							setAccountScene();
							System.gc();
						}
					}
					return false;

				case GAME_SELECT_ACCOUNT:
					if (!isPopup) {
						setMenuScene();
						try {
							sTransitionScene.play();
						} catch (Exception e) {
						}

						gameHandler.post(new Runnable() {

							@Override
							public void run() {
//								adView.loadAd();
							}
						});

						mGameStates = GameStates.GAME_MENU;
						System.gc();
					} else {
						unShowPopUpAccount();
						resetAccount = -1;
					}
					return false;

				case GAME_MENU:
					return false;

				case GAME_WIN:
					return false;

				case GAME_OVER:
					return false;

				default:
					break;
				}

			} else if (pKeyCode == KeyEvent.KEYCODE_MENU) {
				return false;
			} else if (pKeyCode == KeyEvent.KEYCODE_HOME) {
				System.gc();
				return true;
			}

		}
		return super.onKeyDown(pKeyCode, pEvent);

	}

	@Override
	protected void onPause() {
		super.onPause();

		if (!isShowDialogue && !this.mPaused) {
			this.doPause();
		}
	}

	public void onPauseGame() {
		if (loadFinish) {
			pauseMusic();
			if (mGameStates.getValue() == 3)
				pauseGame();

		}
		super.onPauseGame();
	}

	private void pauseMusic() {
		if (mBackgroundMusic.isPlaying())
			try {
				mBackgroundMusic.pause();

			} catch (Exception e) {
			}
		if (mDrum.isPlaying()) {
			mDrum.pause();
		}
		if (mSpellFlying.isPlaying())
			mSpellFlying.pause();
		if (mEnemyMove.isPlaying()) {
			mEnemyMove.pause();
		}
		if (mMenuMusic.isPlaying()) {
			mMenuMusic.pause();
		}
	}

	private void resumeMusic() {
		switch (mGameStates) {
		case GAME_PLAY:
			mBackgroundMusic.play();
			break;

		case GAME_SHOP:
			mMenuMusic.play();
			break;

		case GAME_SELECT_ACCOUNT:
			mMenuMusic.play();
			break;
		default:
			break;
		}
	}

	@Override
	public void onResumeGame() {
		if (isRunning) {
			if (isPause) {
				isPause = false;
				if (loadFinish)
					resumeMusic();
			} else {
				if (loadFinish) {
					resumeMusic();
					if (mGameStates.getValue() == 3)
						pauseGame();
				}
			}
		} else {
			isRunning = true;
		}
//		QplayAchievementUserInfo.getInstance(this, this).onStartGame();
		mEngine.start();
		super.onResumeGame();
	}

	private float mExpFactor = 1;

	private void checkNewBie() {
		gameHandler.post(new Runnable() {

			@Override
			public void run() {
				isShowDialogue = true;
				showDialog(4);
			}
		});
	}

	private void newGame() {
		int countRetry = gameStore.getRetry();

		switch (countRetry) {
		case 0:
			mExpFactor = 1;
			break;

		case 1:
			mExpFactor = 0.75f;
			break;
		case 2:
			mExpFactor = 0.5f;

			break;
		case 3:
			mExpFactor = 0.25f;

			break;
		default:
			mExpFactor = 0.1f;
			break;
		}

		gameStore.setRetry(countRetry + 1);
		onLoadItemSelected();
		onLoadCrossBow(crossBowName, crossBow_index);
		onLoadInforEnemyStage();

		pauseCallEnemy = 0;
		resumeCallEnemy = 0;
		totalPauseGame = 0;
		isDrum = false;
		isSpellFlying = false;
		isUpEnemy = false;
		isAurra = false;

		isPause = false;

	}

	public void pauseGame() {
		if (isRunning) {
			pauseMusic();
			mGameStates = GameStates.GAME_PAUSE;
			mMainScene.setChildScene(pauseGameScene, false, true, true);

			pauseGameScene.setOnSceneTouchListener(this);
			isPause = true;

			pauseCallEnemy = System.currentTimeMillis();

			gameStore.setTime(countTimeGame);
//			QplayAchievementUserInfo.getInstance(this, this).onStopGame();
		}
		mEngine.stop();
	}

	// ============================================================================================================================//
	// LOAD DATAGAME
	// ============================================================================================================================//

	private void onLoadTextFile() {
		ID_Item_Data = new String[Constants.TOTAL_ITEM];
		ID_Skill_Data = new String[Constants.TOTAL_SKILL];

		try {
			readTextFile("data/item_data", ID_Item_Data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			readTextFile("data/skill_data", ID_Skill_Data);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void readTextFile(String nameFile, String... array) throws IOException {
		InputStream input = getApplicationContext().getAssets().open(
				nameFile + ".txt");

		BufferedReader buff = new BufferedReader(new InputStreamReader(input));

		String in = buff.readLine();
		int i = 0;
		while (in != null && i < array.length) {
			array[i] = in;
			i++;
			in = buff.readLine();
		}
		buff.close();
	}

	private void setTextToItemList() {
		StringTokenizer stk = null;

		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			stk = new StringTokenizer(ID_Item_Data[i], ";");

			if (stk.countTokens() != 9) {
//				Log.e("loi doc file", "dong" + i);
//				Log.e("countTokens = ", "" + stk.countTokens());
				return;
			}
			mListItemMenu[i].setPrice(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i].setLimit(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i].setAttack(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i].setDefend(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i].setUpStreng(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i].setUpIntel(Integer.valueOf(stk.nextToken()));
			mListItemMenu[i]
					.setUpArrowVelocity(Integer.valueOf(stk.nextToken()));
			stk.nextToken();
			mListItemMenu[i].setUpArrow(Integer.valueOf(stk.nextToken()));

		}
	}

	private void setTextToSkillList() {
		StringTokenizer stk = null;

		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			String string = ID_Skill_Data[i];
			if (string == null)
				break;
			stk = new StringTokenizer(string, ";");

			if (stk.countTokens() != 5) {
//				Log.e("loi doc file", "dong" + i);
//				Log.e("countTokens = ", "" + stk.countTokens());
				return;
			}
			mListSkillMenu[i].setLimit(Integer.valueOf(stk.nextToken()));
			mListSkillMenu[i].setUseManaString(stk.nextToken());
			mListSkillMenu[i].setCoolDownString(stk.nextToken());
			mListSkillMenu[i].setDamageString(stk.nextToken());
			mListSkillMenu[i].setDelayEnemyString(stk.nextToken());
		}

	}

	private void readEnemyTool(String nameFile, int stage) throws IOException {

		InputStream input = getApplicationContext().getAssets().open(
				nameFile + ".txt");

		BufferedReader buff = new BufferedReader(new InputStreamReader(input));

		String in = buff.readLine();
		// boolean isInterrupt = false;
		boolean isRead = false;

		while (in != null) {
			if (getStageInputLine(in) == stage) {
				mEnemyTool.add(in);
				isRead = true;
			} else if (isRead) {
				break;
			}
			in = buff.readLine();
		}
		buff.close();
	}

	public float calculateExp(String nameFile) throws IOException {
		float exp = 0;

		InputStream input = getApplicationContext().getAssets().open(
				nameFile + ".txt");

		BufferedReader buff = new BufferedReader(new InputStreamReader(input));

		String in = buff.readLine();

		ArrayList<String> enemyTool = new ArrayList<String>();
		ArrayList<Integer> spell = new ArrayList<Integer>();
		ArrayList<Integer> range = new ArrayList<Integer>();
		ArrayList<Integer> melee = new ArrayList<Integer>();
		ArrayList<Integer> tank = new ArrayList<Integer>();
		ArrayList<Integer> aurra = new ArrayList<Integer>();

		while (in != null) {

			enemyTool.add(in);

			in = buff.readLine();
		}
		buff.close();

		StringTokenizer stk1 = null;
		int k = enemyTool.size();
		String input1;

		for (int i = 0; i < k; i++) {
			input1 = enemyTool.get(i);
			stk1 = new StringTokenizer(input1, ";");
			stk1.nextToken();
			melee.add(Integer.valueOf(stk1.nextToken()));
			range.add(Integer.valueOf(stk1.nextToken()));
			tank.add(Integer.valueOf(stk1.nextToken()));
			spell.add(Integer.valueOf(stk1.nextToken()));
			aurra.add(Integer.valueOf(stk1.nextToken()));
		}

		for (int i = 0; i < k; i++) {
			exp += (melee.get(i) * Constants.EXP_MELEE_DEFAULT);
			exp += (range.get(i) * Constants.EXP_RANGE_DEFAULT);
			exp += (tank.get(i) * Constants.EXP_TANK_DEFAULT);
			exp += (spell.get(i) * Constants.EXP_SPELL_DEFAULT);
			exp += (aurra.get(i) * Constants.EXP_AURRA_DEFAULT);
		}
		return exp;
	}

	private int getStageInputLine(String input) {
		StringTokenizer stk = null;

		stk = new StringTokenizer(input, ";");

		int pStage = Integer.valueOf(stk.nextToken());

		return pStage;
	}

	private void setEnemyToolLine() {
		StringTokenizer stk = null;
		int k = mEnemyTool.size();
		String input;

		float factor = 1 + (baseCoefficience - 1) / 4.0f;

		for (int i = 0; i < k; i++) {
			input = mEnemyTool.get(i);
			stk = new StringTokenizer(input, ";");
			stk.nextToken();
			mCountMelee.add(Integer.valueOf(stk.nextToken()));
			mCountRange.add(Integer.valueOf(stk.nextToken()));
			mCountTank.add(Integer.valueOf(stk.nextToken()));
			mCountSpell.add(Integer.valueOf(stk.nextToken()));
			mCountAurra.add(Integer.valueOf(stk.nextToken()));
			mCoolDown.add((long) (Long.valueOf(stk.nextToken()) * factor));

		}
	}

	// ===============================================================================================================================

	// MENUSCENE
	// ===============================================================================================================================

//	private Sprite mBoardInforFree;
//	private Text mSunnetTitle;
//	private Text mInforFree;
//	private MyAnimatedButton mButton;

	private void onLoadMenuScene() {
		mMenuScene = new MyScene();

		createStaticMenuScene();

//		mBoardInforFree = new Sprite(150, 90, mTableWinGame.deepCopy());
//		mSunnetTitle = new Text(50, 30, mFontVietTo,
//				"Phát hành bởi Sunnet ITC!");
//		mSunnetTitle.setColor(0, 0, 0);
//		mInforFree = new Text(60, 100, mFontVietTo, "Hãy chơi và trải nghiệm!",
//				HorizontalAlign.CENTER);
//		mInforFree.setColor(0, 0, 0);
//		mButton = new MyAnimatedButton(EXIT_BOARD_FREE, 340, 310,
//				mPlayTextureRegionE.deepCopy(), this);
//		mButton.setVisible(false);

		mBGMenu = new Sprite(0, 0, mBackgroundAccountTextureRegion);
		mCoLoa_Logo = new Sprite(0, 0, mCoLoaTextureRegion);

		setPositionMenuScene();

		mMenuScene.attachChild(mBGMenu);
		mMenuScene.attachChild(mCoLoa_Logo);

//		mMenuScene.attachChild(mBoardInforFree);
//		mBoardInforFree.attachChild(mSunnetTitle);
//		mBoardInforFree.attachChild(mInforFree);
//		mMenuScene.attachChild(mButton);
//
//		mMenuScene.registerTouchArea(mButton);

		mMenuScene.setOnSceneTouchListener(this);
		mMenuScene.setTouchAreaBindingEnabled(true);
		mMenuScene.setOnSceneTouchListenerBindingEnabled(true);
	}

	private void createStaticMenuScene() {
		mStaticMenuScene = new MenuScene(this.mCamera);

		mPlayMenuItem = new SpriteMenuItem(Constants.PLAY_MENU,
				mPlayTextureRegion);

		mInfoMenuItem = new SpriteMenuItem(Constants.INFO, mInfoTextureRegion);
		mShareMenuItem = new SpriteMenuItem(Constants.SHARE,
				mShareTextureRegion);
		mMoreGameMenuItem = new SpriteMenuItem(Constants.MORE,
				mMoreGameTextureRegion);
		mExitMenuItem = new SpriteMenuItem(Constants.EXIT, mExitTextureRegion);

		mPlayMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		mInfoMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		mMoreGameMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		mMoreGameMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);
		mExitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA,
				GL10.GL_ONE_MINUS_SRC_ALPHA);

		mStaticMenuScene.addMenuItem(mPlayMenuItem);

		mStaticMenuScene.addMenuItem(mInfoMenuItem);
		mStaticMenuScene.addMenuItem(mShareMenuItem);
		mStaticMenuScene.addMenuItem(mMoreGameMenuItem);
		mStaticMenuScene.addMenuItem(mExitMenuItem);

//		mStaticMenuScene.buildAnimations();
		mStaticMenuScene.setBackgroundEnabled(false);
		mStaticMenuScene.setOnMenuItemClickListener(this);
		mStaticMenuScene.setOnSceneTouchListener(this);
		mStaticMenuScene.setTouchAreaBindingEnabled(true);
		mStaticMenuScene.setOnSceneTouchListenerBindingEnabled(true);
	}

	private void setPositionMenuScene() {
		mPlayMenuItem.setPosition(450, 260);
		mInfoMenuItem.setPosition(460, 322);
		mMoreGameMenuItem.setPosition(545, 329);
		mShareMenuItem.setPosition(640, 330);
		mExitMenuItem.setPosition(745, 330);

		mCoLoa_Logo.setPosition(400, 20);
		mBGMenu.setPosition(0, 0);

	}

	private void setMenuScene() {
		mCamera.setCenter(mCameraWidth / 2, mCameraHeight / 2);

		isAccountScene = false;
		isMainGameScene = false;

		setPositionMenuScene();

		if (mMenuMusic.isPlaying())
			mMenuMusic.pause();
		if (mBackgroundMusic.isPlaying()) {
			mBackgroundMusic.pause();
		}

		mEngine.setScene(mMenuScene);

	}

	// ================================================================================================================================
	// //
	// ACCOUNTSCENE
	// ================================================================================================================================
	// //

	private void onLoadAccountScene() {
		mAccountScene = new MyScene();

		isLoadedDataAccount = new boolean[3];

		background_Account = new Sprite(0, 0, mBackgroundAccountTextureRegion);
		mAccountScene.attachChild(background_Account);

		onLoadAccountMenuScene();

		gameAccountLevel = new int[3];

		generalLevelAccount = new ChangeableText[3];
		countRetry = new ChangeableText[3];

		Coin_Text = new ChangeableText[3];
		Coin_General = new int[3];
		generalName = new ChangeableText[3];
		stageAccount = new ChangeableText[3];
		timeAccount = new ChangeableText[3];

		for (int i = 0; i < 3; i++) {
			timeAccount[i] = new ChangeableText(40 + i * 258, 300, mFontViet1,
					"Time : 1 năm 2 tháng \r\n 3 ngày 4 giờ");
			generalName[i] = new ChangeableText(40, 0, mFontViet1,
					"Dịch Hu Tống", HorizontalAlign.CENTER,
					"xxxx Dịch Hu Tống ".length());
			generalName[i].setScale(1.2f);
			generalName[i].setColor(0, 0, 0);
			countRetry[i] = new ChangeableText(0, 0, mFontViet1,
					"Đã chơi : xxxx");
			stageAccount[i] = new ChangeableText(0, 0, mFontViet1, "Hồi : xx");

			Coin_General[i] = mGameSrotes[i].getMoney();

			Coin_Text[i] = new ChangeableText(0, 0, mFontViet1, "ốc "
					+ Coin_General[i], 15);
			Coin_Text[i].setBlendFunction(GL10.GL_SRC_ALPHA,
					GL10.GL_ONE_MINUS_SRC_ALPHA);

			gameAccountLevel[i] = mGameSrotes[i].getGeneral(generalLastUsed[i])
					.getLevel();

			generalLevelAccount[i] = new ChangeableText(0, 0, mFontViet1,
					"Cấp độ : xx " + gameAccountLevel[i]);

			mAccountScene.attachChild(generalLevelAccount[i]);
			mAccountScene.attachChild(Coin_Text[i]);
			mAccountScene.attachChild(generalName[i]);
			mAccountScene.attachChild(stageAccount[i]);
			mAccountScene.attachChild(timeAccount[i]);
			mAccountScene.attachChild(countRetry[i]);
		}

		Sprite ac1 = new Sprite(40, 340, mSnailCoinIcon.deepCopy());
		Sprite ac2 = new Sprite(295, 340, mSnailCoinIcon.deepCopy());
		Sprite ac3 = new Sprite(550, 340, mSnailCoinIcon.deepCopy());

		mAccountScene.attachChild(ac1);
		mAccountScene.attachChild(ac2);
		mAccountScene.attachChild(ac3);

		onLoadPopupScene();

		mAccountScene.setOnSceneTouchListener(this);
		mAccountScene.setTouchAreaBindingEnabled(true);
		mAccountScene.setOnSceneTouchListenerBindingEnabled(true);
	}

	private Sprite mBoardPopupAccount;
	private boolean isPopup = false;

	private void onLoadAccountMenuScene() {

		int[] account = { Constants.ACCOUNT_01, Constants.ACCOUNT_02,
				Constants.ACCOUNT_03 };

		contain_account = new MyTiledButton[3];
		mResetAccount = new MyTiledButton[3];
		mAccountIcon = new MyTiledButton[3];

		for (int i = 0; i < 3; i++) {
			mResetAccount[i] = new MyTiledButton(reset[i], this,
					mContainAccountResetTextureRegion);
			Text resetText = new Text(50, 10, mFontViet, "Thiết lập lại");
			resetText.setColor(0, 0, 0);
			resetText.setScale(1.2f);
			mResetAccount[i].attachChild(resetText);
			mAccountScene.attachChild(mResetAccount[i]);

			contain_account[i] = new MyTiledButton(account[i], this,
					mContainAccountTextureRegion);
			mAccountScene.attachChild(contain_account[i]);

			mAccountIcon[i] = new MyTiledButton(i + 3, this,
					mDichHuTong_IconTextureRegion);
			mAccountIcon[i].setPosition(50, 40);
			contain_account[i].attachChild(mAccountIcon[i]);

			mAccountScene.registerTouchArea(mResetAccount[i]);
			mAccountScene.registerTouchArea(contain_account[i]);
		}

	}

	private CameraScene mPopUpScene;
	private static final String RESET_WARNING = "Bạn có chắc chắn \n thiết lập lại?\r\n Tất cả dữ liệu bị xóa trừ số ốc!";

	private void onLoadPopupScene() {
		mPopUpScene = new CameraScene(mCamera);

		mBoardPopupAccount = new Sprite(300, 150, mBoardInfoSmall);

		Text warning = new Text(0, 0, mFontViet, RESET_WARNING,
				HorizontalAlign.CENTER);
		warning.setColor(0.8f, 0, 0);

		final MyAnimatedButton yes = new MyAnimatedButton(YES_POPUP, 20, 130,
				mYesTiledTextureRegion.deepCopy(), this);
		final MyAnimatedButton no = new MyAnimatedButton(NO_POPUP, 150, 130,
				mNoTiledTextureRegion.deepCopy(), this);

		mBoardPopupAccount.setScale(0);
		mBoardPopupAccount.attachChild(no);
		mBoardPopupAccount.attachChild(yes);
		mBoardPopupAccount.attachChild(warning);
		mPopUpScene.attachChild(mBoardPopupAccount);
		warning.setPosition(0, 10);

		mPopUpScene.registerTouchArea(no);
		mPopUpScene.registerTouchArea(yes);

		mPopUpScene.setOnSceneTouchListener(this);
		mPopUpScene.setBackgroundEnabled(false);
		mPopUpScene.setTouchAreaBindingEnabled(true);
		mPopUpScene.setOnSceneTouchListenerBindingEnabled(true);
	}

	private void setPositionAccountScene() {
		for (int i = 0; i < 3; i++) {
			contain_account[i].setPosition(12 + 258 * i, 20);
			mResetAccount[i].setPosition(12 + i * 258, 400);
			generalName[i].setPosition(80 + i * 255, 200);
			stageAccount[i].setPosition(40 + i * 255, 260);
			Coin_Text[i].setPosition(100 + i * 255, 340);
			generalLevelAccount[i].setPosition(80 + i * 255, 230);
			countRetry[i].setPosition(145 + i * 255, 260);
		}
	}

	
	private void setAccountScene() {
		mCamera.setCenter(mCameraWidth / 2, mCameraHeight / 2);

		mGameStates = GameStates.GAME_SELECT_ACCOUNT;

		isAccountScene = true;
		isMainGameScene = false;

		text.setVisible(false);
		mStageText.setVisible(false);

		setPositionAccountScene();

		for (int i = 0; i < 3; i++) {
			int general = mGameSrotes[i].getGeneralLastUsed();
			mAccountIcon[i].setTextureRegion(mGeneralIcon[general]);
			generalLevelAccount[i].setText("Cấp độ "
					+ String.valueOf(mGameSrotes[i].getGeneral(general)
							.getLevel()));
			countRetry[i].setText("Đã chơi: " + mGameSrotes[i].getRetry());
			generalName[i].setText(Constants.GENERAL_NAME[general]);
			stageAccount[i].setText("Hồi : "
					+ String.valueOf(mGameSrotes[i].getStage() + 1));
			Coin_Text[i].setText(" x "
					+ String.valueOf(mGameSrotes[i].getMoney()));

			long time = mGameSrotes[i].getTime()/1000;

			long hour = time / 3600;
			time = time - hour * 3600;
			long minus = time / 60;
			time = time - minus * 60;
			long second = time;
			
			timeAccount[i].setText("Time : " + hour + "h " + minus + "ph "
					+ second + "s");
		}

		reLoadGeneralLastUsedAccount();

		// try {
		// float exp = calculateExp("data/tool_call_enemy");
		// Log.e("total", ""+exp);
		// } catch (IOException e) {
		// Log.e("khong doc duoc", "khong doc duoc");
		// e.printStackTrace();
		// }

//		gameHandler.post(new Runnable() {
//
//			@Override
//			public void run() {
//				adView.setVisibility(View.GONE);
//			}
//		});

		mMenuMusic.play();

		mEngine.setScene(mAccountScene);
	}
	
	private boolean isReLoadGenralUseAccount = false;

	private void reLoadGeneralLastUsedAccount() {
		if (!isReLoadGenralUseAccount) {
			return;
		}

		mAccountIcon[ACCOUNT]
				.setTextureRegion(mGeneralIcon[generalLastUsed[ACCOUNT]]);

		gameAccountLevel[ACCOUNT] = mGameSrotes[ACCOUNT].getGeneral(
				generalLastUsed[ACCOUNT]).getLevel();

		isReLoadGenralUseAccount = false;
	}

	// =============================================================================================================================

	// EquipmentScene

	// =============================================================================================================================

	private void onLoadEquipmentScene() {

		mEquipmentScene = new MyScene();
		mInformationScene = new CameraScene(mCamera);
		mRemoveSkillScene = new MenuScene(mCamera);
		mUpgradeGeneralScene = new CameraScene(mCamera);
		mPriceSnailScene = new CameraScene(mCamera);

		backgroundSplite = new Sprite(0, 0,
				mBackgroundSpliteGeneralTextureRegion);

		mEquipmentScene.attachChild(backgroundSplite);

		ID_Item_List_Store = new int[Constants.TOTAL_ITEM];

		onLoadEquipmentHUD();

		createGeneralList();

		contain_select = new Rectangle(490, 66, 290, 330);
		contain_select.setColor(0, 0, 0);
		mEquipmentScene.attachChild(contain_select);

		createItemBox();
		createSkillBox();

		background_equipment = new Sprite(0, 0, mBackgroundTextureRegion);

		contain = new Contain[4];

		contain_gold = new MyAnimatedButton(CONTAIN_SNAIL, pX, pY,
				mContainGoldTextureRegion, this);

		Sprite snail = new Sprite(25, 10, mSnailCoinIcon.deepCopy());

		totalGold_display = new ChangeableText(100, 15, mFontViet1, "", 9);
		contain_gold.attachChild(totalGold_display);
		contain_gold.attachChild(snail);

		contain[0] = new Contain(0, 0, mContainMenu.deepCopy());
		contain[1] = new Contain(0, 0, mContainMenu.deepCopy());
		contain[2] = new Contain(0, 0, mContainMenu.deepCopy());
		contain[3] = new Contain(0, 0, mContainMenu.deepCopy());

		taytuykinh = new Sprite(0, 0, mTaytuykinhTextureRegion);

		play = new MyAnimatedButton(PLAY_GAME, 660, 425, mPlayTextureRegionE,
				this);

		select_skill = new MyAnimatedButton(SELECT_SKILL, pX, pY,
				mSkillSelectTextureRegion, this);

		select_item = new MyAnimatedButton(SELECT_ITEM, pX, pY,
				mItemSelectTextureRegion, this);

		background_equipment.setZIndex(3);

		contain[0].setZIndex(4);
		contain[1].setZIndex(4);
		contain[2].setZIndex(4);
		contain[3].setZIndex(4);

		taytuykinh.setZIndex(4);

		play.setZIndex(4);
		contain_gold.setZIndex(4);
		select_item.setZIndex(4);
		select_skill.setZIndex(4);

		setTextToItemList();
		setTextToSkillList();

		mEquipmentScene.attachChild(background_equipment);

		scrollLeft = new MyTiledButton(SCROLL_LEFT, -5, -100, this,
				mScrollTextureRegion);
		scrollRight = new MyTiledButton(SCROLL_RIGHT, 240, -100, this,
				mScrollTextureRegion.deepCopy());
		scrollLeft.setFlippedHorizontal(true);

		mWarningUpgrade = new MyAnimatedButton(UP_WARNING, 230, 10,
				mPlusTiledTextureRegion.deepCopy(), this);

		contain_index = new Sprite(5, 300, mBoardInfoSmall);

		mGeneralName = new ChangeableText(20, 10, mFontVietTo, "Dịch Hu Tống",
				HorizontalAlign.CENTER, "An Dương Vương".length());

		mHPGeneralUse = new ChangeableText(5, 75, mFontViet1, "",
				"xxxx/xxxxxxxxxxxxxxxxxxxxxxxxxxxx".length());
		mHPGeneralUse.setColor(0.6f, 0, 0);
		mMPGeneralUse = new ChangeableText(5, 100, mFontViet1, "",
				"xxxx/xxxxxxxxxxxxxxxxxxxxxxxxxxx".length());
		mMPGeneralUse.setColor(0, 0, 1);
		mEXPGeneralUse = new ChangeableText(5, 125, mFontViet1, "",
				"Kinh nghiệm       :  100000 / 100000".length());
		mEXPGeneralUse.setColor(1, 0.68f, 0);
		mLevelGeneral = new ChangeableText(5, 50, mFontViet1,
				"Level         : 0",
				"level xxxxxxxxxxxxxxxxxxxxxxxxxx".length());
		mLevelGeneral.setColor(1f, 0.68f, 0);

		contain_index.attachChild(scrollLeft);
		contain_index.attachChild(scrollRight);

		contain_index.setZIndex(3);
		contain_index.attachChild(mHPGeneralUse);
		contain_index.attachChild(mMPGeneralUse);
		contain_index.attachChild(mEXPGeneralUse);
		contain_index.attachChild(mLevelGeneral);
		contain_index.attachChild(mWarningUpgrade);
		contain_index.attachChild(mGeneralName);

		mEquipmentScene.attachChild(contain_index);

		mEquipmentScene.attachChild(taytuykinh);
		mEquipmentScene.attachChild(contain[0]);
		mEquipmentScene.attachChild(contain[1]);
		mEquipmentScene.attachChild(contain[2]);
		mEquipmentScene.attachChild(contain[3]);

		mEquipmentScene.registerTouchArea(play);
		mEquipmentScene.registerTouchArea(contain_gold);
		mEquipmentScene.registerTouchArea(select_item);
		mEquipmentScene.registerTouchArea(select_skill);
		mEquipmentScene.registerTouchArea(mWarningUpgrade);

		mEquipmentScene.attachChild(play);
		mEquipmentScene.attachChild(contain_gold);
		mEquipmentScene.attachChild(select_skill);
		mEquipmentScene.attachChild(select_item);

		mScrollDetector = new SurfaceScrollDetector(this);
		mClickDetector = new ClickDetector(this);

		mEquipmentScene.setOnSceneTouchListener(this);
		mEquipmentScene.setTouchAreaBindingEnabled(true);
		mEquipmentScene.setOnSceneTouchListenerBindingEnabled(true);

		onLoadInforScene();
		onLoadRemoveSkillScene();
		onLoadUpgradeGeneralScene();
		onLoadPriceSnail();
	}

	private Sprite mBoardPriceSnail;
	private MyAnimatedButton mPlusSkill;
	private MyAnimatedButton mPlusBasic;
	private MyAnimatedButton mNapOc;
	private MyAnimatedButton mExitBoardPriceSnail;
	// private MyAnimatedButton mYesBoradPriceSnail;

	private ChangeableText mTotalSnail;
	private ChangeableText mBuyablePointSkill;
	private ChangeableText mBuyablePointBasic;

	private void onLoadPriceSnail() {
		mBoardPriceSnail = new Sprite(287, 49, mBoardInfo.deepCopy());

		mPlusSkill = new MyAnimatedButton(BUY_SKILL_POINT, 280, 200,
				mPlusTiledTextureRegion.deepCopy(), this);
		mPlusBasic = new MyAnimatedButton(BUY_BASIC_POINT, 280, 120,
				mPlusTiledTextureRegion.deepCopy(), this);

		mNapOc = new MyAnimatedButton(BUY_SNAIL, 370, 20,
				mPayTiledTextureRegion, this);
		mExitBoardPriceSnail = new MyAnimatedButton(EXIT_BOARD_PRICE, 200, 300,
				mBigReturnTiledTextureRegion, this);
		// mYesBoradPriceSnail = new MyAnimatedButton(YES_BOARD_PRICE, 80, 300,
		// mBigYesTiledTextureRegion, this);

		mBuyablePointSkill = new ChangeableText(210, 200, mFontVietTo, "0", 8);
		mBuyablePointSkill.setColor(0.8f, 0.7f, 0.4f);
		mBuyablePointBasic = new ChangeableText(210, 120, mFontVietTo, "0", 8);
		mBuyablePointBasic.setColor(0.8f, 0.7f, 0.4f);

		mTotalSnail = new ChangeableText(190, 20, mFontVietTo, "", 12);

		final Text snailToSkillPoint = new Text(400, 195, mFontVietTo, "x "
				+ Constants.PRICE_SKILL_POINT);
		snailToSkillPoint.setColor(0.8f, 0.7f, 0.4f);
		final Text snailToBasicPoint = new Text(400, 115, mFontVietTo, "x "
				+ Constants.PRICE_BASIC_POINT);
		snailToBasicPoint.setColor(0.8f, 0.7f, 0.4f);
		final Text pointSkill = new Text(20, 120, mFontVietTo,
				"Điểm cơ bản   : ");
		final Text pointBasic = new Text(20, 200, mFontVietTo,
				"Điểm kĩ năng : ");

		final Sprite mSnailTotal = new Sprite(130, 20,
				mSnailCoinIcon.deepCopy());
		final Sprite mSnailSkill = new Sprite(340, 120,
				mSnailCoinIcon.deepCopy());
		final Sprite mSnailBasic = new Sprite(340, 200,
				mSnailCoinIcon.deepCopy());

		mPriceSnailScene.attachChild(mBoardPriceSnail);

		mPriceSnailScene.registerTouchArea(mPlusBasic);
		mPriceSnailScene.registerTouchArea(mPlusSkill);
		mPriceSnailScene.registerTouchArea(mNapOc);
		mPriceSnailScene.registerTouchArea(mExitBoardPriceSnail);
		// mPriceSnailScene.registerTouchArea(mYesBoradPriceSnail);

		mPriceSnailScene.setOnSceneTouchListener(this);
		mPriceSnailScene.setBackgroundEnabled(false);
		mPriceSnailScene.setTouchAreaBindingEnabled(true);
		mPriceSnailScene.setOnSceneTouchListenerBindingEnabled(true);

		mBoardPriceSnail.attachChild(mPlusBasic);
		mBoardPriceSnail.attachChild(mExitBoardPriceSnail);
		// mBoardPriceSnail.attachChild(mYesBoradPriceSnail);
		mBoardPriceSnail.attachChild(mPlusSkill);
		mBoardPriceSnail.attachChild(mNapOc);
		mBoardPriceSnail.attachChild(mTotalSnail);
		mBoardPriceSnail.attachChild(mBuyablePointBasic);
		mBoardPriceSnail.attachChild(mBuyablePointSkill);
		mBoardPriceSnail.attachChild(mSnailTotal);
		mBoardPriceSnail.attachChild(mSnailSkill);
		mBoardPriceSnail.attachChild(mSnailBasic);
		mBoardPriceSnail.attachChild(snailToSkillPoint);
		mBoardPriceSnail.attachChild(snailToBasicPoint);
		mBoardPriceSnail.attachChild(pointBasic);
		mBoardPriceSnail.attachChild(pointSkill);

	}

	private void onLoadUpgradeGeneralScene() {
		mBoardUpgrade = new Sprite(287, 49, mBoardInfo);

		mPlusUpgradeStreng = new MyAnimatedButton(UP_STRENG, 400, 140,
				mPlusTiledTextureRegion.deepCopy(), this);
		mPlusUpgradeAgility = new MyAnimatedButton(UP_AGILITY, 400, 195,
				mPlusTiledTextureRegion.deepCopy(), this);
		mPlusUpgradeIntel = new MyAnimatedButton(UP_INTEL, 400, 250,
				mPlusTiledTextureRegion.deepCopy(), this);

		mCompleteUpgrade = new MyAnimatedButton(UP_COMPLETE, 300, 300,
				mReturnTiledTextureRegion.deepCopy(), this);

		pointAgility = new ChangeableText(300, 200, mFontViet1, "",
				"xxxxx".length());
		pointStreng = new ChangeableText(300, 140, mFontViet1, "",
				"xxxxx".length());
		pointIntel = new ChangeableText(300, 255, mFontViet1, "",
				"xxxxx".length());

		pointBasic = new ChangeableText(300, 30, mFontVietTo, "",
				"xxxxx".length());
		pointSkill = new ChangeableText(300, 80, mFontVietTo, "",
				"xxxxx".length());
		pointBasic.setColor(1, 0.68f, 0);
		pointSkill.setColor(1, 0.68f, 0);

		final Text pBasicPoin = new Text(50, 20, mFontVietTo, "Điểm cơ bản");
		pBasicPoin.setScale(1.4f);
		pBasicPoin.setColor(1, 0.68f, 0);
		final Text pSkillPoin = new Text(50, 70, mFontVietTo, "Điểm kĩ năng");
		pSkillPoin.setScale(1.4f);
		pSkillPoin.setColor(1, 0.68f, 0);
		final Text pStrengPoin = new Text(50, 130, mFontVietTo, "Sức mạnh");
		pStrengPoin.setScale(1.1f);
		final Text pAgilityPoin = new Text(50, 190, mFontVietTo, "Tốc độ");
		pAgilityPoin.setScale(1.1f);
		final Text pIntelPoin = new Text(50, 245, mFontVietTo, "Thông minh");
		pIntelPoin.setScale(1.1f);

		mBoardUpgrade.attachChild(pBasicPoin);
		mBoardUpgrade.attachChild(pSkillPoin);
		mBoardUpgrade.attachChild(pStrengPoin);
		mBoardUpgrade.attachChild(pAgilityPoin);
		mBoardUpgrade.attachChild(pIntelPoin);
		mBoardUpgrade.attachChild(mPlusUpgradeAgility);
		mBoardUpgrade.attachChild(mPlusUpgradeStreng);
		mBoardUpgrade.attachChild(mPlusUpgradeIntel);
		mBoardUpgrade.attachChild(mCompleteUpgrade);
		mBoardUpgrade.attachChild(pointAgility);
		mBoardUpgrade.attachChild(pointStreng);
		mBoardUpgrade.attachChild(pointIntel);
		mBoardUpgrade.attachChild(pointSkill);
		mBoardUpgrade.attachChild(pointBasic);
		mUpgradeGeneralScene.attachChild(mBoardUpgrade);

		mUpgradeGeneralScene.registerTouchArea(mPlusUpgradeAgility);
		mUpgradeGeneralScene.registerTouchArea(mPlusUpgradeStreng);
		mUpgradeGeneralScene.registerTouchArea(mPlusUpgradeIntel);
		mUpgradeGeneralScene.registerTouchArea(mCompleteUpgrade);

		mUpgradeGeneralScene.setOnSceneTouchListener(this);
		mUpgradeGeneralScene.setBackgroundEnabled(false);
		mUpgradeGeneralScene.setTouchAreaBindingEnabled(true);
		mUpgradeGeneralScene.setOnSceneTouchListenerBindingEnabled(true);

	}

	private void onLoadInforScene() {
		containTotalAssets = new Sprite(287, 49, mBoardInfo);
		containTotalAssets.setScale(0);
		item_selected = new Sprite(24, 24, mListItemTextureRegions[0]);
		contain_selected = new Sprite(20, 20, mContainMenu.deepCopy());

		mContainInforItem = new Rectangle(0, 0, containTotalAssets.getWidth(),
				containTotalAssets.getHeight());
		mContainInforItem.setAlpha(0);
		mContainInforSkill = new Rectangle(0, 0, mContainInforItem.getWidth(),
				containTotalAssets.getHeight());
		mContainInforSkill.setAlpha(0);
		nameItem = new ChangeableText(120, 20, mFontVietTo, Name_Shop[10],
				"Linh quang kim \r\n trảo thần nỏ".length());
		nameItem.setColor(0.8f, 0.6f, 0.2f);

		final Text price = new Text(20, 250, mFontViet, "Giá              :");
		price.setColor(1, 0.4f, 0.4f);
		priceText = new ChangeableText(150, 250, mFontViet1, "xxxxxxxxxxx");

		final Text level = new Text(20, 100, mFontViet, "Cấp độ       :");
		level.setColor(1, 0.4f, 0.4f);
		bounderyText = new ChangeableText(150, 100, mFontViet1, "xxxxxx");

		final Text streng = new Text(20, 150, mFontViet, "Sức mạnh  :");
		streng.setColor(1, 0.4f, 0.4f);
		upAttackText = new ChangeableText(150, 150, mFontViet, "xxxxxx");

		final Text agility = new Text(270, 200, mFontViet, "Tốc độ          :");
		agility.setColor(1, 0.4f, 0.4f);
		upArrowVelocityText = new ChangeableText(400, 200, mFontViet1, "xxxxxx");

		final Text HP = new Text(270, 100, mFontViet, "Sinh lực       :");
		HP.setColor(1, 0.4f, 0.4f);
		upStrengText = new ChangeableText(400, 100, mFontViet1, "xxxxxx");

		final Text MP = new Text(270, 150, mFontViet, "Năng lượng :");
		MP.setColor(1, 0.4f, 0.4f);
		upIntelText = new ChangeableText(400, 150, mFontViet1, "xxxxxx");

		final Text defend = new Text(20, 200, mFontViet1, "Phòng thủ  :");
		defend.setColor(1, 0.4f, 0.4f);
		upDefendText = new ChangeableText(150, 200, mFontViet1, "xxxxxx");

		final Text arrow = new Text(270, 250, mFontViet1, "Mũi tên        :");
		arrow.setColor(1, 0.4f, 0.4f);
		upArrowText = new ChangeableText(400, 250, mFontViet1, "xxxxxxxxxxx");

		final Text damage = new Text(40, 135, mFontViet,
				"Damage                 :");
		damage.setColor(1, 0.4f, 0.4f);
		attackTextSkill = new ChangeableText(240, 135, mFontViet1, "+ 50000");
		nextDamage = new ChangeableText(290, 135, mFontViet1,
				" xxxxxxxxxxxxxxxxxxx");
		nextDamage.setColor(1, 1, 1);

		final Text useMana = new Text(40, 170, mFontViet,
				"Năng lượng           :");
		useMana.setColor(1, 0.4f, 0.4f);
		useManaTextSkill = new ChangeableText(240, 170, mFontViet1,
				"XXXxxxturn");
		nextManaUse = new ChangeableText(290, 170, mFontViet1, " next 10000");

		final Text levelUse = new Text(40, 100, mFontViet,
				"Cấp độ Tướng       :");
		levelUse.setColor(1, 0.4f, 0.4f);
		bounderyTextSkill = new ChangeableText(240, 100, mFontViet1, "XXXxxx");

		final Text coolDown = new Text(40, 205, mFontViet,
				"Hồi chiêu               :");
		coolDown.setColor(1, 0.4f, 0.4f);
		coolDownTextSkill = new ChangeableText(240, 205, mFontViet1,
				"xxxxxxxxxxx");
		nextTurn = new ChangeableText(290, 205, mFontViet1, " next 500 s");

		levelSkillInfor = new ChangeableText(150, 50, mFontViet1,
				"level : xx/xx");
		levelSkillInfor.setColor(0.8f, 0.6f, 0.2f);

		Text timeDelayText = new Text(40, 240, mFontViet, "Làm chậm kẻ thù :");
		timeDelayText.setColor(1, 0.4f, 0.4f);
		timeDelayEnemy = new ChangeableText(240, 240, mFontViet1,
				"level : xx/xx");
		nextDelayEnemy = new ChangeableText(290, 240, mFontViet1, " next  500s");
		nextDelayEnemy.setColor(1, 1, 1);

		mPointSkill = new Text(40, 275, mFontViet, "Điểm kĩ năng còn :");
		mPointSkill.setColor(1, 1, 1);
		pointSkillInfor = new ChangeableText(240, 275, mFontViet1, "xxxx");

		up = new MyAnimatedButton(UP, 170, 320,
				mUpgradeTiledTextureRegion.deepCopy(), this);
		buy = new MyAnimatedButton(PLUS, 30, 320,
				mBuyTiledTextureRegion.deepCopy(), this);
		use = new MyAnimatedButton(PLUS, 30, 320,
				mUseTiledTextureRegion.deepCopy(), this);
		returnSprite = new MyAnimatedButton(DESTROY, 300, 320,
				mReturnTiledTextureRegion.deepCopy(), this);

		sale = new MyAnimatedButton(SALE, 170, 320, mSaleTiledTextureRegion,
				this);

		mInformationScene.attachChild(containTotalAssets);
		containTotalAssets.attachChild(returnSprite);
		containTotalAssets.attachChild(use);
		containTotalAssets.attachChild(buy);
		containTotalAssets.attachChild(mContainInforItem);
		containTotalAssets.attachChild(mContainInforSkill);
		mInformationScene.registerTouchArea(up);
		mInformationScene.registerTouchArea(use);
		mInformationScene.registerTouchArea(buy);
		mInformationScene.registerTouchArea(sale);
		mInformationScene.registerTouchArea(returnSprite);
		containTotalAssets.attachChild(item_selected);
		containTotalAssets.attachChild(contain_selected);
		containTotalAssets.attachChild(nameItem);

		mContainInforSkill.attachChild(up);
		mContainInforSkill.attachChild(coolDownTextSkill);
		mContainInforSkill.attachChild(attackTextSkill);
		mContainInforSkill.attachChild(useManaTextSkill);
		mContainInforSkill.attachChild(bounderyTextSkill);
		mContainInforSkill.attachChild(timeDelayText);
		mContainInforSkill.attachChild(timeDelayEnemy);
		mContainInforSkill.attachChild(pointSkillInfor);
		mContainInforSkill.attachChild(levelSkillInfor);
		mContainInforSkill.attachChild(damage);
		mContainInforSkill.attachChild(levelUse);
		mContainInforSkill.attachChild(mPointSkill);
		mContainInforSkill.attachChild(coolDown);
		mContainInforSkill.attachChild(useMana);
		mContainInforSkill.attachChild(nextManaUse);
		mContainInforSkill.attachChild(nextTurn);
		mContainInforSkill.attachChild(nextDelayEnemy);
		mContainInforSkill.attachChild(nextDamage);

		mContainInforItem.attachChild(sale);
		mContainInforItem.attachChild(upAttackText);
		mContainInforItem.attachChild(upDefendText);
		mContainInforItem.attachChild(upStrengText);
		mContainInforItem.attachChild(upIntelText);
		mContainInforItem.attachChild(bounderyText);
		mContainInforItem.attachChild(upArrowVelocityText);
		mContainInforItem.attachChild(upArrowText);
		mContainInforItem.attachChild(priceText);
		mContainInforItem.attachChild(streng);
		mContainInforItem.attachChild(level);
		mContainInforItem.attachChild(price);
		mContainInforItem.attachChild(agility);
		mContainInforItem.attachChild(arrow);
		mContainInforItem.attachChild(HP);
		mContainInforItem.attachChild(MP);
		mContainInforItem.attachChild(defend);

		// mContainInforItem.attachChild(upArrowSprite);
		// mContainInforItem.attachChild(upDefendSprite);
		// mContainInforItem.attachChild(upStrengSprite);
		// mContainInforItem.attachChild(upArrowVelocity);
		// mContainInforItem.attachChild(snailSprite);

		mInformationScene.setOnSceneTouchListener(this);
		mInformationScene.setBackgroundEnabled(false);
		mInformationScene.setTouchAreaBindingEnabled(true);
		mInformationScene.setOnSceneTouchListenerBindingEnabled(true);
	}

	private ChangeableText mQuantity;

	private void onLoadRemoveSkillScene() {
		containTaytuykinh = new Sprite(345, 65, mContainTaytuykinhTextureRegion);
		taytuykinh_remove = new Sprite(15, 20,
				mTaytuykinhTextureRegion.deepCopy());
		final Text name = new Text(100, 5, mFontVietTo, "Tẩy tủy kinh");
		mQuantity = new ChangeableText(100, 40, mFontVietTo, " x xxx");
		mQuantity.setColor(1, 0, 0);
		final MyAnimatedButton buyRemoveSkillItem = new MyAnimatedButton(
				DETAIL_REMOVE_SKILL, 300, 10, mDetailTiledTextureRegion, this);

		Sprite containTayTuyKinh = new Sprite(10, 15, mContainMenu.deepCopy());

		isSelectRemove = new boolean[] { false, false, false };

		int[] checkRemove = { CHECK_REMOVE_0, CHECK_REMOVE_1, CHECK_REMOVE_2 };

		mSkill_Remove = new Sprite[3];
		mContain_Skill_Remove = new Sprite[3];
		checkRemoveSkill = new MyRadioButton[3];

		for (int i = 0; i < 3; i++) {
			mSkill_Remove[i] = new Sprite(105 + i * 100, 125,
					mListSkillTextureRegions[0]);
			mContain_Skill_Remove[i] = new Sprite(100 + i * 100, 120,
					mContainMenu);
			containTaytuykinh.attachChild(mContain_Skill_Remove[i]);

			checkRemoveSkill[i] = new MyRadioButton(checkRemove[i],
					155 + i * 100, 105, mRemovableTextureRegion.deepCopy(),
					mRemovable_select_TextureRegion.deepCopy());
			mRemoveSkillScene.addMenuItemList(checkRemoveSkill[i]);

			containTaytuykinh.attachChild(mSkill_Remove[i]);
			containTaytuykinh.attachChild(checkRemoveSkill[i]);
		}

		completeRemoveSkill = new MyAnimatedButton(COMPLETE_REMOVE, 120, 270,
				mYesTiledTextureRegion.deepCopy(), this);
		destroy_remove = new MyAnimatedButton(DESTROY_REMOVE, 270, 270,
				mReturnTiledTextureRegion, this);

		mRemoveSkillScene.attachChild(containTaytuykinh);
		containTaytuykinh.attachChild(taytuykinh_remove);
		containTaytuykinh.attachChild(containTayTuyKinh);
		containTaytuykinh.attachChild(completeRemoveSkill);
		containTaytuykinh.attachChild(destroy_remove);
		containTaytuykinh.attachChild(name);
		containTaytuykinh.attachChild(mQuantity);
		containTaytuykinh.attachChild(buyRemoveSkillItem);

		mRemoveSkillScene.registerTouchArea(completeRemoveSkill);
		mRemoveSkillScene.registerTouchArea(destroy_remove);
		mRemoveSkillScene.registerTouchArea(buyRemoveSkillItem);

		mRemoveSkillScene.setOnSceneTouchListener(this);
		mRemoveSkillScene.setBackgroundEnabled(false);
		mRemoveSkillScene.setOnSceneTouchListenerBindingEnabled(true);
		mRemoveSkillScene.setTouchAreaBindingEnabled(true);
		mRemoveSkillScene.setOnMenuItemClickListener(this);

		onLoadPopupRemoveSkill();
	}

	private Sprite mBoardPopupRemoveSkill;
	private ChangeableText totalSnailPopupRemoveSkill;
	private ChangeableText quantity;
	private CameraScene mPopupRemoveSkill;

	private void onLoadPopupRemoveSkill() {
		mPopupRemoveSkill = new CameraScene(mCamera);

		mBoardPopupRemoveSkill = new Sprite(287, 49, mBoardInfo);

		Sprite mSnail = new Sprite(130, 5, mSnailCoinIcon);
		totalSnailPopupRemoveSkill = new ChangeableText(180, 5, mFontVietTo,
				" x 1000000000");

		Sprite tayTuyKinhImage = new Sprite(20, 65, mTaytuykinhTextureRegion);
		Sprite containTayTuyKinh = new Sprite(15, 60, mContainMenu);

		Text tayTuyKinh = new Text(110, 60, mFontVietTo, "Tẩy tủy kinh");
		Text specific = new Text(
				60,
				135,
				mFontViet1,
				"Một kĩ năng chỉ có thể sử dụng bởi một tướng.\r\nTẩy tủy kinh dùng để xóa kĩ năng đã h�?c.\r\n trả lại số điểm kĩ năng đã dùng để nâng cấp",
				HorizontalAlign.CENTER);
		quantity = new ChangeableText(110, 100, mFontViet1, "Hiện có : xxxxxxx");

		Sprite pSnail = new Sprite(280, 260, mSnailCoinIcon);
		Text priceRemoveSkill = new Text(90, 255, mFontVietTo, "Giá    : "
				+ Constants.PRICE_REMOVE_SKILL + " x ");

		final MyAnimatedButton mBuyButton = new MyAnimatedButton(
				BUY_REMOVE_SKILL_POPUP, 380, 260, mBuyTiledTextureRegion, this);
		final MyAnimatedButton mReturnButton = new MyAnimatedButton(
				EXIT_REMOVE_SKILL_POPUP, 210, 320, mReturnTiledTextureRegion,
				this);
		final MyAnimatedButton mPayButton = new MyAnimatedButton(
				PAY_SNAIL_REMOVE_SKILL_POPUP, 375, 10, mPayTiledTextureRegion,
				this);

		mPopupRemoveSkill.attachChild(mBoardPopupRemoveSkill);
		mBoardPopupRemoveSkill.attachChild(mBuyButton);
		mBoardPopupRemoveSkill.attachChild(mReturnButton);
		mBoardPopupRemoveSkill.attachChild(quantity);
		mBoardPopupRemoveSkill.attachChild(specific);
		mBoardPopupRemoveSkill.attachChild(tayTuyKinh);
		mBoardPopupRemoveSkill.attachChild(tayTuyKinhImage);
		mBoardPopupRemoveSkill.attachChild(containTayTuyKinh);
		mBoardPopupRemoveSkill.attachChild(mSnail);
		mBoardPopupRemoveSkill.attachChild(totalSnailPopupRemoveSkill);
		mBoardPopupRemoveSkill.attachChild(pSnail);
		mBoardPopupRemoveSkill.attachChild(priceRemoveSkill);
		mBoardPopupRemoveSkill.attachChild(mPayButton);
		mBoardPopupRemoveSkill.setScale(0);

		mPopupRemoveSkill.registerTouchArea(mBuyButton);
		mPopupRemoveSkill.registerTouchArea(mReturnButton);
		mPopupRemoveSkill.registerTouchArea(mPayButton);

		mPopupRemoveSkill.setOnSceneTouchListener(this);
		mPopupRemoveSkill.setBackgroundEnabled(false);
		mPopupRemoveSkill.setOnSceneTouchListenerBindingEnabled(true);
		mPopupRemoveSkill.setTouchAreaBindingEnabled(true);
	}

	private boolean isPopupRemoveSkill = false;
	private boolean isChildScene = false;

	private void showPopupRemoveSkill() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isChildScene = true;
				isPopupRemoveSkill = true;
				reLoadPopupRemoveSkill(false);
				mEquipmentScene.setChildScene(mPopupRemoveSkill, false, true,
						false);

				mBoardPopupRemoveSkill.setScaleCenter(
						mBoardPopupRemoveSkill.getWidth() / 2,
						mBoardPopupRemoveSkill.getHeight() / 2);
				mBoardPopupRemoveSkill
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0.5f, 1)));
			}
		});
	}

	private void unShowPopupRemoveSkill() {
		sButtonClicked.play();
		isPopupRemoveSkill = false;
		isChildScene = false;
		mEquipmentScene.clearChildScene();
		mBoardPopupRemoveSkill.setScale(0.5f);

	}

	private ChangeableText mHPGeneralUse;
	private ChangeableText mMPGeneralUse;
	private ChangeableText mEXPGeneralUse;
	private ChangeableText mLevelGeneral;
	private ChangeableText mGeneralName;

	private void onLoadEquipmentHUD() {

		text = new Text(10, 5, mFontVietTo, "Hãy chọn một cây nỏ phù hợp");
		text.setColor(0, 0, 0);
		text.setVisible(false);

		useGeneral = new ChangeableText(10, 5, mFontVietTo, "",
				HorizontalAlign.CENTER,
				"Ban chua du dieu kien de su dung tuong tiep theo xxxxxxxxxxxxxxxxxx"
						.length());
		useGeneral.setColor(0, 0, 0);
		useGeneral.setVisible(false);

		hud.attachChild(useGeneral);
		hud.attachChild(text);
	}

	private void setPositionEquipmentScene() {

		backgroundSplite.setPosition(13, 0);
		background_equipment.setPosition(0, 0);

		contain_index.setInitialPosition();

		play.setPosition(660, 425);
		select_item.setPosition(320, 8);
		select_skill.setPosition(538, 8);

		contain_gold.setPosition(290, 425);

		taytuykinh.setPosition(350, 73);

		contain[0].setPosition(345, 73);
		contain[1].setPosition(345,
				mContainMenu.getHeight() + contain[0].getY() + 5);
		contain[2].setPosition(345,
				mContainMenu.getHeight() + contain[1].getY() + 5);
		contain[3].setPosition(345,
				mContainMenu.getHeight() + contain[2].getY() + 5);

		mGenerals[0].setPosition(13 - generalUse * 275, 0);
		mGenerals[1].setPosition(288 - generalUse * 275, 0);
		mGenerals[2].setPosition(573 - generalUse * 275, 0);

		contain_select.setPosition(pX, pY);

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		MySprite sprite;
		SkillMenu skill_menu;
		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			skill_menu = mListSkillMenu[i];
			skill_menu.resetPosition();
			sprite = mContainSkillList[i];
			sprite.setPosition(sprite.xFinal, sprite.yFinal);
			sprite = mListLockSkillList[i];
			sprite.setPosition(sprite.xFinal, sprite.yFinal);
		}
		ItemMenu item_menu;
		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			item_menu = mListItemMenu[i];
			item_menu.resetPosition();
			sprite = mContainItemList[i];
			sprite.setPosition(sprite.xFinal, sprite.yFinal);
			sprite = mListLockItemList[i];
			sprite.setPosition(sprite.xFinal, sprite.yFinal);
		}

		for (Contain _contain : contain) {
			if (_contain.isContainItem()) {
				mListItemMenu[_contain.getIdItem() - totalSkill].setPosition(
						_contain.getX() + 5, _contain.getY() + 5);
				mListItemMenu[_contain.getIdItem() - totalSkill].setpX(_contain
						.getX() + 10);
				mListItemMenu[_contain.getIdItem() - totalSkill].setpY(_contain
						.getY() + 5);
			}
		}

		for (Contain _contain : contain) {
			if (_contain.isContainSkill()) {
				mListSkillMenu[_contain.getIdSkill()].setPosition(
						_contain.getX() + 5, _contain.getY() + 5);
				mListSkillMenu[_contain.getIdSkill()]
						.setpX(_contain.getX() + 5);
				mListSkillMenu[_contain.getIdSkill()]
						.setpY(_contain.getY() + 5);
			}
		}

		// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	}

	private void setEquipmentScene() {
		mCamera.setCenter(mCameraWidth / 2, mCameraHeight / 2);

		mGameStates = GameStates.GAME_SHOP;

		onLoadGameAccountStore();
		loadTool();

		generalUse = gameStore.getGeneralLastUsed();

		generalStore = gameStore.getGeneral(generalUse);

		if (isAccountScene) {
			isItemMenu = false;
			select_item.setVisible(true);
			select_skill.setVisible(true);

			resetContainMenu();
			resetPositionListMenu();
			onLoadEquipmentMenuAccount();

			select_item.setCurrentTileIndex(0);
			select_skill.setCurrentTileIndex(1);
			isItemMenu = false;
			taytuykinh.setVisible(true);
		}

		reLoadGeneralInfo(true);

		setPositionEquipmentScene();

		totalGold = gameStore.getMoney();

		totalGold_display.setText("x " + String.valueOf(totalGold));

		isMainGameScene = false;
		isAccountScene = false;

		isGeneralScroll = false;
		isSkillScroll = false;
		isItemScroll = false;

		mLevelGeneral.setText("Cấp độ          : "
				+ String.valueOf(gameStore.getGeneral(
						gameStore.getGeneralLastUsed()).getLevel()));

		text.setVisible(false);

		if (!mMenuMusic.isPlaying())
			mMenuMusic.play();

		for (int i = 0; i < 3; i++) {
			idSkillUse[i] = -1;
		}

		warningUpGeneral();

		try {
			if (mBackgroundMusic.isPlaying()) {
				mBackgroundMusic.pause();
			}

			if (!mMenuMusic.isPlaying()) {
				mMenuMusic.pause();
			}

		} catch (Exception e) {
		}

		mEngine.setScene(mEquipmentScene);
		System.gc();
	}

	private void loadTool() {
		if (lastGameStage == stage && stage > 0)
			return;
		mEnemyTool.clear();
		mCountMelee.clear();
		mCountRange.clear();
		mCountTank.clear();
		mCountAurra.clear();
		mCountSpell.clear();
		mCoolDown.clear();

		int loadStage = stage % 20;

		if (loadStage < 7 && stage > 19) {
			loadStage += 7;
		}

		try {
			readEnemyTool("data/tool_call_enemy", loadStage);
		} catch (IOException e) {
			e.printStackTrace();
		}
		setEnemyToolLine();
	}

	// ///////////////////////////////////////////////////////////////////////

	private void createSkillBox() {
		int countE = 0;

		float pXItem = pX;
		float pYItem = pY;

		int i = 0;
		int k = 0;

		while (countE < Constants.TOTAL_SKILL) {
			k = countE / 3;
			i = countE % 3;
			final int skill_ID = countE;

			pXItem = pX + i * mContainMenu.getWidth() + PADDING * i + 5;
			pYItem = pY + k * mContainMenu.getHeight() + PADDING * k + 5;

			mContainSkillList[countE] = new MySprite(2, pXItem, pYItem,
					mContainMenu.deepCopy());

			mListLockSkillList[countE] = new MySprite(2, pXItem + 2,
					pYItem + 2, mLockMenu.deepCopy());

			mListSkillMenu[countE] = new SkillMenu(skill_ID, 1, pXItem + 5,
					pYItem + 5, mListSkillTextureRegions[i + k * 3]);
			mListSkillMenu[countE].setName(Name_Shop[countE]);

			if (countE % 2 == 0)
				mListSkillMenu[countE].setState(false);
			else
				mListSkillMenu[countE].setState(true);

			mEquipmentScene.attachChild(mListSkillMenu[countE]);
			mEquipmentScene.attachChild(mListLockSkillList[countE]);
			mEquipmentScene.attachChild(mContainSkillList[countE]);

			mListLockSkillList[countE].setVisible(false);

			countE++;

		}
		mCamera_MaxY_ScrollSkill = pYItem - mCameraHeight + 50;
	}

	private void createItemBox() {
		int countE = 0;
		int kind = 0;

		float pXItem = pX;
		float pYItem = pY;
		int i = 0;
		int k = 0;

		while (countE < Constants.TOTAL_ITEM) {
			k = countE / 3;
			i = countE % 3;
			final int item_ID = countE + Constants.TOTAL_SKILL;

			pXItem = pX + i * mContainMenu.getWidth() + PADDING * i + 5;
			pYItem = pY + k * mContainMenu.getHeight() + PADDING * k + 5;

			if (countE < 5)
				kind = Constants.ITEM_NO;
			else if (countE >= 5 && countE < 8)
				kind = Constants.ITEM_MU;
			else if (countE >= 8 && countE < 11)
				kind = Constants.ITEM_AOGIAP;
			else if (countE >= 11 && countE < 14)
				kind = Constants.ITEM_GIAPTAY;

			mListLockItemList[countE] = new MySprite(2, pXItem + 2, pYItem + 2,
					mLockMenu.deepCopy());

			mContainItemList[countE] = new MySprite(2, pXItem, pYItem,
					mContainMenu.deepCopy());

			mListItemMenu[countE] = new ItemMenu(kind, item_ID, 1, pXItem + 5,
					pYItem + 5, mListItemTextureRegions[i + k * 3]);

			mEquipmentScene.attachChild(mListItemMenu[countE]);
			mEquipmentScene.attachChild(mContainItemList[countE]);
			mListItemMenu[countE].setVisible(false);
			mContainItemList[countE].setVisible(false);

			mEquipmentScene.attachChild(mListLockItemList[countE]);
			mListLockItemList[countE].setVisible(false);

			countE++;
		}
		mCamera_MaxY_ScrollItem = pYItem - mCameraHeight;
	}

	private void createGeneralList() {

		mGenerals = new Sprite[3];

		mGenerals[0] = new Sprite(0, 0, mDichHuTongTextureRegion);
		mGenerals[1] = new Sprite(0, 0, mCaoLoTextureRegion);
		mGenerals[2] = new Sprite(0, 0, mAnDuongVuongTextureRegion);

		mEquipmentScene.attachChild(mGenerals[0]);
		mEquipmentScene.attachChild(mGenerals[1]);
		mEquipmentScene.attachChild(mGenerals[2]);

	}

	// ////////////////////Load Equip khi vao
	// EquipmentScene//////////////////////

	private void setUnLockListItem(boolean isUnLockable) {
		if (!isUnLockable)
			return;
		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			if (generalStore.getLevel() < mListItemMenu[i].getLimit()) {
				mListItemMenu[i].setLock(true);
				mListItemMenu[i].setUnlock(false);
				mListLockItemList[i].setTextureRegion(mLockMenu);
			} else if (mListItemMenu[i].isLock()) {
				mListItemMenu[i].setUnlock(true);
				mListLockItemList[i].setTextureRegion(mUnLockMenu);
			}
		}
	}

	private void setUnLockListSkill(boolean isUnLockable) {
		if (!isUnLockable)
			return;

		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			int k = mListSkillMenu[i].getLimit();
			if (generalStore.getLevel() < k) {
				mListSkillMenu[i].setLock(true);
				mListSkillMenu[i].setUnlock(false);
				mListLockSkillList[i].setTextureRegion(mLockMenu);
			} else {
				mListSkillMenu[i].setUnlock(true);
				mListLockSkillList[i].setTextureRegion(mUnLockMenu);
			}
		}
	}

	private void onLoadItemStore() {
		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			ID_Item_List_Store[i] = gameStore.getIDItem(i);
			if (ID_Item_List_Store[i] != -1) {
				mListItemMenu[i].setLock(false);
			}
		}
	}

	private void onLoadSkillGeneralUsed() {
		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			ID_Skill_Store[i] = gameStore.getIDSkillGeneralUsed(i);
		}
	}

	private void onLoadGeneralSkill() {
		for (int i = 0; i < 3; i++) {
			ID_Skill_Use[i] = generalStore.getSkillUsed(i);
		}
	}

	private void onLoadGameItem() {
		for (int i = 0; i < 4; i++) {
			ID_Item_Use[i] = gameStore.getIDItemUsed(i);
		}
	}

	private void onLoadEquipmentMenuAccount() {
		onLoadSkillGeneralUsed();

		onLoadItemStore();

		onLoadGameItem();
		onLoadGeneralSkill();

		int level = generalStore.getLevel();

		/*
		 * Item
		 */

		ItemMenu item;
		for (int i = 0; i < totalItem; i++) {
			item = mListItemMenu[i];
			item.setContainBy(-1);
			if (ID_Item_List_Store[i] != -1) {
				mListLockItemList[i].setVisible(false);
				item.setLock(false);
				item.setUnlock(true);
			} else {
				if (item.getLimit() > level) {
					item.setLock(true);
					item.setUnlock(false);
					mListLockItemList[i].setTextureRegion(mLockMenu);
				} else {
					item.setLock(true);
					item.setUnlock(true);
					mListLockItemList[i].setTextureRegion(mUnLockMenu);
				}
			}

			item.setVisible(false);
			mListLockItemList[i].setVisible(false);
			mContainItemList[i].setVisible(false);
		}

		for (int i = 0; i < 4; i++) {
			if (ID_Item_Use[i] != -1) {
				item = mListItemMenu[ID_Item_Use[i] - Constants.TOTAL_SKILL];

				if (item.getLimit() > level) {

					contain[i].setContainItem(false);
					contain[i].setIdItem(-1);
					contain[i].setKindOfEquipmentItem(-1);

					item.setPosition(item.xPos, item.yPos);
					item.setpX(item.xPos);
					item.setpY(item.yPos);

					item.setContainBy(-1);
					item.setZIndex(1);
					mEquipmentScene.sortChildren();

					gameStore.removeItemUsed(i);
					gameStore.removeItem(item.getID());

				} else {

					item.setpX(contain[i].getX() + 5);
					item.setpY(contain[i].getY() + 5);
					item.setPosition(contain[i].getX() + 5,
							contain[i].getY() + 5);

					item.setZIndex(5);
					mEquipmentScene.sortChildren();
					item.setContainBy(i);

					contain[i].setKindOfEquipmentItem(item.kindOfEquipment);
					contain[i].setContainItem(true);
					contain[i].setIdItem(item.getID());
				}
			}
		}

		/*
		 * Skill
		 */
		SkillMenu skill;

		for (int i = 0; i < totalSkill; i++) {
			skill = mListSkillMenu[i];

			int temp = ID_Skill_Store[i];
			if (temp != -1) {
				mListLockSkillList[i].setVisible(false);
				skill.setLock(false);
				skill.setUnlock(true);
				if (temp == generalUse) {
					skill.setVisible(true);
				} else {
					skill.setVisible(false);
				}

			} else {
				skill.setVisible(true);
				skill.setLevel(1);
				mListLockSkillList[i].setVisible(true);
				if (skill.getLimit() > level) {
					skill.setLock(true);
					skill.setUnlock(false);
					mListLockSkillList[i].setTextureRegion(mLockMenu);
				} else {
					skill.setLock(true);
					skill.setUnlock(true);
					mListLockSkillList[i].setTextureRegion(mUnLockMenu);
				}
			}
			mContainSkillList[i].setVisible(true);
		}

		for (int i = 0; i < 3; i++) {
			if (ID_Skill_Use[i] != -1) {
				skill = mListSkillMenu[ID_Skill_Use[i]];
				skill.setLevel(generalStore.getLevelSkillUsed(i));
				skill.setContainBy(i + 1);

				skill.setpX(contain[i + 1].getX() + 5);
				skill.setpY(contain[i + 1].getY() + 5);
				skill.setPosition(contain[i + 1].getX() + 5,
						contain[i + 1].getY() + 5);

				skill.setZIndex(5);
				mEquipmentScene.sortChildren();

				contain[i + 1].setContainSkill(true);
				contain[i + 1].setIdSkill(skill.getID());
				contain[i + 1].setState(skill.getState());
			}
		}

	}

	// ///////////////////////////////////////////////////////////////////////////////////////

	private void resetPositionListMenu() {
		synchronized (mListSkillMenu) {
			for (SkillMenu skill_menu : mListSkillMenu) {
				skill_menu.resetPosition();
				skill_menu.resetZIndex();
				skill_menu.resetInfomation();
			}
		}

		synchronized (mListItemMenu) {
			for (ItemMenu item_menu : mListItemMenu) {
				item_menu.resetPosition();
				item_menu.resetZIndex();
				item_menu.resetInfomation();
			}
		}

		synchronized (mContainItemList) {
			for (MySprite sprite : mContainItemList) {
				sprite.resetPosition();
			}
		}

		synchronized (mContainSkillList) {
			for (MySprite sprite : mContainItemList) {
				sprite.resetPosition();
			}
		}

		synchronized (mListLockItemList) {
			for (MySprite sprite : mListLockItemList) {
				sprite.resetPosition();
			}
		}

		synchronized (mListLockSkillList) {
			for (MySprite sprite : mListLockSkillList) {
				sprite.resetPosition();
			}
		}
	}

	private void resetContainMenu() {
		synchronized (contain) {
			for (Contain _contain : contain) {
				_contain.resetContain();
			}
		}
	}

	private int testEquipment() {
		for (int i = 0; i < 4; i++) {
			if (contain[i].getKindOfEquipmentItem() == Constants.ITEM_NO)
				return i;
		}

		return -1;
	}

	private int testContainSkill(StateSkill state) {
		int count = 0;
		int index = 0;

		for (int i = 1; i < 4; i++) {
			if (!contain[i].isContainSkill()) {
				index = i;
				break;
			}
		}

		if (index != 0) {
			for (int i = 1; i < 4; i++) {
				if (contain[i].isContainSkill()) {
					if (contain[i].getState() == state)
						count++;
				}
			}
			if (state == StateSkill.ACTIVE && count < 2)
				return index;
			else if (state == StateSkill.PASSIVE && count == 0)
				return index;

		}
		return -1;
	}

	private int testContainItem(int kind) {
		for (int i = 0; i < 4; i++) {
			if (!contain[i].isContainItem()) {
				for (int j = 0; j < 4 && contain[j].isContainItem() && j != i; j++) {
					if (contain[j].getKindOfEquipmentItem() == kind)
						return -1;
				}
				return i;
			}
		}
		return -1;
	}

	// ///////////////////////////////////////////////////////////////////////////////////////

	private synchronized void onClickItemMenu(final float pDistanceX,
			final float pDistanceY) {
		if (isInforScene || isChildScene)
			return;
		ItemMenu item;
		for (int i = 0; i < totalItem; i++) {
			item = mListItemMenu[i];
			if (!item.contains(pDistanceX, pDistanceY) || !item.isVisible())
				continue;
			sButtonClicked.play();

			if (!item.isLock()) {

				sale.setVisible(true);
				isBuy = false;
				final int k = testContainItem(item.kindOfEquipment);

				if (k == -1 || item.getLimit() > generalStore.getLevel()) {
					buy.setVisible(false);
					use.setVisible(false);
					isUsedItem = false;
				} else if (item.getLimit() <= generalStore.getLevel()) {
					isUsedItem = true;
					buy.setVisible(false);
					use.setVisible(true);
				}
			} else {
				sale.setVisible(false);
				isNeedPaySnail = true;
				if (item.isUnlock()) {
					if (item.getPrice() <= totalGold) {
						isNeedPaySnail = false;
					}
					isBuy = true;
					isUsedItem = false;
					buy.setVisible(true);
					use.setVisible(false);
				} else {
					isBuy = false;
					isUsedItem = false;
					buy.setVisible(false);
					use.setVisible(false);
				}
			}
			up.setVisible(false);
			itemClicked = item;
			isInforScene = true;

			showInforItem(item);
			break;
		}
	}

	private void useItem(ItemMenu item) {
		final int k = testContainItem(item.kindOfEquipment);
		if (k != -1) {
			item.setContainBy(k);
			item.setpX(contain[k].getX() + 5);
			item.setpY(contain[k].getY() + 5);
			item.setZIndex(5);
			mEquipmentScene.sortChildren();
			item.setPosition(contain[k].getX() + 5, contain[k].getY() + 5);

			contain[k].setKindOfEquipmentItem(item.kindOfEquipment);
			contain[k].setContainItem(true);
			contain[k].setIdItem(item.getID());

			gameStore.useItem(k, item.getID());
			gameStore.newItem(item.getID());

		}
	}

	private void sale(int id) {
		ItemMenu item = mListItemMenu[id - totalSkill];
		int price = item.getPrice() / 2;

		totalGold = totalGold + price;
		totalGold_display.setText(String.valueOf(totalGold));
		gameStore.buyGold(price);

		int index = item.getContainBy();

		if (index != -1) {
			contain[index].setContainItem(false);
			contain[index].setIdItem(-1);
			contain[index].setKindOfEquipmentItem(-1);
			gameStore.removeItem(id);
			item.setContainBy(-1);
			gameStore.removeItemUsed(index);
		}

		item.setZIndex(1);

		item.setPosition(item.xPos, item.yPos);
		item.setpX(item.xPos);
		item.setpY(item.yPos);
		item.setLock(true);
		item.setUnlock(true);

		mListLockItemList[id - totalSkill].setTextureRegion(mUnLockMenu);
		mListLockItemList[id - totalSkill].setVisible(true);

		gameStore.removeItem(id);
	}

	private boolean pay() {
		int coin = totalGold - itemClicked.getPrice();

		if (coin < 0)
			return false;

		totalGold = totalGold - itemClicked.getPrice();
		gameStore.pay(itemClicked.getPrice());
		gameStore.newItem(itemClicked.getID());
		mListLockItemList[itemClicked.getID() - Constants.TOTAL_SKILL]
				.setVisible(false);
		itemClicked.setLock(false);
		totalGold_display.setText(String.valueOf(totalGold));

		Coin_General[ACCOUNT] = gameStore.getMoney();
		Coin_Text[ACCOUNT].setText("Gold " + Coin_General[ACCOUNT]);
		timeAccount[ACCOUNT].setText("Time : " + gameStore.getTime());

		return true;
	}

	private void showInforItem(final ItemMenu item) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isChildScene = true;

				mEquipmentScene.setChildScene(mInformationScene, false, true,
						true);

				item_selected.setTextureRegion(item.getTextureRegion()
						.deepCopy());
				nameItem.setText(Name_Shop[item.getID()]);

				containTotalAssets.setScaleCenter(
						containTotalAssets.getWidth() / 2,
						containTotalAssets.getHeight() / 2);
				containTotalAssets
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0.5f, 1)));

				mContainInforItem.setVisible(true);
				mContainInforSkill.setVisible(false);
				upAttackText.setText("+" + String.valueOf(item.getAttack()));
				upDefendText.setText("+" + String.valueOf(item.getDefend()));
				bounderyText.setText(" " + String.valueOf(item.getLimit()));
				upStrengText.setText("+" + String.valueOf(item.getUpStreng()));
				upArrowVelocityText.setText("+"
						+ String.valueOf(item.getUpArrowVelocity()) + "%");
				upIntelText.setText("+" + String.valueOf(item.getUpIntel()));
				upArrowText.setText("+" + String.valueOf(item.getUpArrow()));
				priceText.setText(" " + String.valueOf(item.getPrice()));
				isLockScene = true;
				isInforScene = true;
			}
		});
	}

	private void unShowInfoItem() {
		isChildScene = false;

		mEquipmentScene.clearChildScene();
		containTotalAssets.setScale(0.5f);
		isInforScene = false;
		isBuy = false;
		isUsedItem = false;
		itemClicked = null;
		isLockScene = false;
	}

	private synchronized void onClickSkillMenu(final float pDistanceX,
			final float pDistanceY) {
		if (isInforScene || isChildScene)
			return;

		for (final SkillMenu skill_menu : mListSkillMenu) {
			if (!skill_menu.contains(pDistanceX, pDistanceY)
					|| !skill_menu.isVisible())
				continue;
			sButtonClicked.play();
			final int k = testContainSkill(skill_menu.getState());

			if (!skill_menu.isLock()) {
				isLearning = false;
				use.setVisible(true);
				isNeedPaySnail = false;
			} else {
				if (skill_menu.isUnlock()) {
					isLearning = true;
					use.setVisible(true);
				} else {
					isLearning = false;
					use.setVisible(false);
				}
				up.setVisible(false);
			}

			if (k == -1) {
				isUsedSkill = false;
				use.setVisible(false);

			} else {
				isUsedSkill = true;
			}

			buy.setVisible(false);
			skillClicked = skill_menu;
			isInforScene = true;
			showInfoSkill(skill_menu);

			break;
		}
	}

	private boolean learnSkill() {
		if (generalStore.getPointUpSkill() < 1)
			return false;
		int id = skillClicked.getID();
		mListLockSkillList[id].setVisible(false);
		skillClicked.setLock(false);
		return true;
	}

	private void useSkill(SkillMenu skill_menu) {
		if (generalStore.getPointUpSkill() < 1)
			return;

		final int k = testContainSkill(skill_menu.getState());
		if (k != -1) {
			skill_menu.setpX(contain[k].getX() + 5);
			skill_menu.setpY(contain[k].getY() + 5);
			skill_menu.setZIndex(5);
			skill_menu.setContainBy(k);

			mEquipmentScene.sortChildren();
			skill_menu
					.setPosition(contain[k].getX() + 5, contain[k].getY() + 5);

			contain[k].setContainSkill(true);
			contain[k].setIdSkill(skill_menu.getID());
			contain[k].setState(skill_menu.getState());

			generalStore.setSkillUsed(k - 1, skill_menu.getID());
			gameStore.setIDSkillGeneralUsed(skill_menu.getID(),
					generalStore.getName());

			generalStore.setPointUpSkill(1, false);

			ID_Skill_Store[skill_menu.getID()] = generalStore.getName();

			int p = generalStore.getPointUpSkill();
			if (p == 0) {
				pointSkillInfor.setColor(1, 1, 1);
				mPointSkill.setColor(1, 1, 1);
			} else {
				pointSkillInfor.setColor(1, 0, 0);
				mPointSkill.setColor(1, 0, 0);
			}

			pointSkillInfor.setText("" + p);
		}
	}

	private void unShowInforSkill() {
		isChildScene = false;
		mEquipmentScene.clearChildScene();
		containTotalAssets.setScale(0.5f);
		isInforScene = false;
		isLearning = false;
		isUsedItem = false;
		skillClicked = null;
		isLockScene = false;
	}

	private void showInfoSkill(final SkillMenu skill_menu) {

		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isChildScene = true;
				mEquipmentScene.setChildScene(mInformationScene, false, true,
						true);

				nameItem.setText(Name_Shop[skill_menu.getID()]);

				item_selected.setTextureRegion(skill_menu.getTextureRegion()
						.deepCopy());

				containTotalAssets.setScaleCenter(
						containTotalAssets.getWidth() / 2,
						containTotalAssets.getHeight() / 2);
				containTotalAssets
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0.5f, 1)));

				changeInforSkillScene(skill_menu.getID());

				mContainInforItem.setVisible(false);
				mContainInforSkill.setVisible(true);
				isLockScene = true;
				isInforScene = true;
			}
		});
	}

	private void changeInforSkillScene(int id) {
		SkillMenu skill = mListSkillMenu[id];

		if (id == 0) {
			attackTextSkill
					.setText("+" + (int) (skill.getDamage() * 100) + "%");
			if (skill.getLevel() == skill.getMaxLevel()) {
				nextDamage.setText("damage");
			} else {
				nextDamage.setText(" next  " + (int) (skill.nextDamage * 100)
						+ "% damage");
			}
		} else {
			attackTextSkill.setText("+" + (int) (skill.getDamage()));
			if (skill.getLevel() == skill.getMaxLevel()) {
				nextDamage.setText("");
			} else {
				nextDamage.setText(" next  " + (int) skill.nextDamage);
			}
		}
		useManaTextSkill.setText("- " + (int) (skill.getUseMana()));

		if (skill.getUseMana() > (generalStore.getIntelligent() * 10 + 50)) {
			useManaTextSkill.setColor(1, 0, 0);
			nextManaUse.setColor(1, 0, 0);
		} else {
			useManaTextSkill.setColor(1, 1, 1);
		}

		if (skill.nextManaUse > (generalStore.getIntelligent() * 10 + 50)) {
			nextManaUse.setColor(1, 0, 0);
		} else {
			nextManaUse.setColor(1, 1, 1);
		}
		if (skill.getLevel() == skill.getMaxLevel()) {
			nextManaUse.setText(" ");
		} else {
			nextManaUse.setText(" next  " + (int) skill.nextManaUse);
		}

		if (skill.getLevel() == skill.getMaxLevel()) {
			nextTurn.setText(" ");
		} else {
			nextTurn.setText(" next  " + skill.nextTurn + "s");
		}

		bounderyTextSkill.setText("+" + String.valueOf(skill.getLimit()));
		coolDownTextSkill.setText(String.valueOf(skill.getCoolDown()) + "s");
		timeDelayEnemy.setText(String.valueOf(skill.getDelay()) + "s");
		levelSkillInfor.setText("level " + String.valueOf(skill.getLevel())
				+ "/" + String.valueOf(skill.getMaxLevel()));

		if (skill.getLevel() == skill.getMaxLevel()) {
			nextDelayEnemy.setText("");
		} else {
			nextDelayEnemy.setText(" next  " + skill.nextDelayEnemy + "s");
		}

		int k = generalStore.getPointUpSkill();
		if (k == 0) {
			pointSkillInfor.setColor(1, 1, 1);
			mPointSkill.setColor(1, 1, 1);
		} else {
			pointSkillInfor.setColor(1, 0, 0);
			mPointSkill.setColor(1, 0, 0);
		}
		pointSkillInfor.setText("" + k);
	}

	private boolean upgradeSkill(int index) {
		if (generalStore.getPointUpSkill() < 1)
			return false;
		if (index == -1)
			return false;
		SkillMenu skill = mListSkillMenu[contain[index].getIdSkill()];

		if (skill.getMaxLevel() <= skill.getLevel())
			return false;
		generalStore.upLevelSkillUsed(index - 1);
		generalStore.setPointUpSkill(1, false);

		skill.setLevel(generalStore.getLevelSkillUsed(index - 1));

		changeInforSkillScene(skill.getID());

		return true;
	}

	private void buyRemoveSkill() {
		if (gameStore.getMoney() >= Constants.PRICE_REMOVE_SKILL) {
			sButtonClicked.play();
			gameStore.buyTayTuyKinh(1);
			gameStore.pay(Constants.PRICE_REMOVE_SKILL);
			reLoadPopupRemoveSkill(true);
		}
	}

	private void reLoadPopupRemoveSkill(boolean isTotal) {
		totalGold = gameStore.getMoney();
		totalSnailPopupRemoveSkill.setText(" x " + totalGold);
		quantity.setText("Hiện có : " + gameStore.getcTayTuyKinh());
		if (isTotal) {
			totalGold_display.setText(" x " + totalGold);
		}
	}

	private void showRemove() {
		isChildScene = true;
		mQuantity.setText(" x " + gameStore.getcTayTuyKinh());
		for (int i = 0; i < 3; i++) {
			int ID = generalStore.getSkillUsed(i);
			if (ID != -1) {
				isSelectRemove[i] = false;
				mSkill_Remove[i].setVisible(true);
				checkRemoveSkill[i].setVisible(true);
				checkRemoveSkill[i].setCheck(false);
				mSkill_Remove[i].setTextureRegion(mListSkillMenu[ID]
						.getTextureRegion().deepCopy());
			} else {
				mSkill_Remove[i].setVisible(false);
				checkRemoveSkill[i].setVisible(false);
			}
		}

		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				mEquipmentScene.setChildScene(mRemoveSkillScene, false, true,
						true);
				containTaytuykinh.setVisible(true);
				containTaytuykinh.setScaleCenter(0, 0);
				containTaytuykinh.setScale(0.01f, 0.01f);

				containTaytuykinh.registerEntityModifier(new ScaleAtModifier(
						0.3f, 0.01f, 1.0f, 0, 0));
			}
		});
		selectRemoveSkill = false;
		// isLockScene = true;
	}

	private void unShowRemoveSkill(final boolean isRemove) {
		for (int i = 0; i < 3; i++) {
			checkRemoveSkill[i].updateTextureRegion(
					mRemovableTextureRegion.deepCopy(), true);
		}
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				if (removeSkill(isRemove)) {
					mEquipmentScene.clearChildScene();
					isRemoveSkill = false;
					isChildScene = false;
				}
			}
		});
	}

	private boolean removeSkill(final boolean isRemove) {
		if (!isRemove)
			return true;
		for (int i = 0; i < 3; i++) {
			if (isSelectRemove[i]) {
				if (gameStore.getcTayTuyKinh() <= 0)
					return false;
				if (isRemove) {
					gameStore.useTayTuyKinh();

					contain[i + 1].setContainSkill(false);
					contain[i + 1].setIdSkill(-1);
					contain[i + 1].setState(StateSkill.NORMAL);

					SkillMenu skill_menu = mListSkillMenu[generalStore
							.getSkillUsed(i)];
					skill_menu.setPosition(skill_menu.xPos, skill_menu.yPos);
					skill_menu.setpX(skill_menu.xPos);
					skill_menu.setpY(skill_menu.yPos);
					skill_menu.setContainBy(-1);

					skill_menu.setZIndex(1);
					skill_menu.setLock(true);
					skill_menu.setUnlock(true);

					generalStore.setPointUpSkill(skill_menu.getLevel() - 1,
							true);

					skill_menu.setLevel(1);

					mListLockSkillList[skill_menu.getID()].setVisible(true);
					mListLockSkillList[skill_menu.getID()]
							.updateTextureRegion(mUnLockMenu);

					pointSkillInfor
							.setText("" + generalStore.getPointUpSkill());

					ID_Skill_Store[skill_menu.getID()] = -1;

					gameStore.setIDSkillGeneralUsed(
							generalStore.getSkillUsed(i), -1);
					generalStore.removeSkillUsed(i);

					isSelectRemove[i] = false;
					checkRemoveSkill[i]
							.setTextureRegion(mRemovableTextureRegion);
				}
			}
		}
		return true;
	}

	private void onSelect() {
		sButtonClicked.play();

		if (isItemMenu) {
			SkillMenu skill_menu;
			for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
				skill_menu = mListSkillMenu[i];
				skill_menu.setVisible(false);
				mContainSkillList[i].setVisible(false);
				mListLockSkillList[i].setVisible(false);
			}

			ItemMenu item_menu;
			for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
				item_menu = mListItemMenu[i];
				item_menu.setVisible(true);
				mContainItemList[i].setVisible(true);
				if (item_menu.isLock() && !mListLockItemList[i].isVisible()) {
					mListLockItemList[i].setVisible(true);
				}
			}
			select_item.setCurrentTileIndex(1);
			select_skill.setCurrentTileIndex(0);
			taytuykinh.setVisible(false);
		} else {
			SkillMenu skill_menu;
			for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
				skill_menu = mListSkillMenu[i];
				skill_menu.setVisible(true);
				if (ID_Skill_Store[i] != generalUse && ID_Skill_Store[i] != -1) {
					skill_menu.setVisible(false);
					if (mListLockSkillList[i].isVisible())
						mListLockSkillList[i].setVisible(false);
				}
				mContainSkillList[i].setVisible(true);
				if (skill_menu.isLock() && !mListLockSkillList[i].isVisible())
					mListLockSkillList[i].setVisible(true);
			}

			ItemMenu item_menu;
			for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
				item_menu = mListItemMenu[i];
				item_menu.setVisible(false);
				mContainItemList[i].setVisible(false);
				mListLockItemList[i].setVisible(false);
			}
			select_item.setCurrentTileIndex(0);
			select_skill.setCurrentTileIndex(1);
			taytuykinh.setVisible(true);
		}
	}

	// ///////////////////////////////////////////////////////////////////////////////////////

	private void scrollSkillBox(final float pDistanceX, final float pDistanceY) {
		if (isInforScene)
			return;
		if (((mCamera_CurentY - pDistanceY) < mCamera_MinY_ScrollSkill + 10)) {
			return;
		} else if ((mCamera_CurentY - pDistanceY) > mCamera_MaxY_ScrollSkill + 120) {
			return;
		}

		this.mCamera.offsetCenter(0, -pDistanceY);
		mCamera_CurentY -= pDistanceY;

		this.mGenerals[2].setPosition(mGenerals[2].getX(), mGenerals[2].getY()
				- pDistanceY);
		this.mGenerals[1].setPosition(mGenerals[1].getX(), mGenerals[1].getY()
				- pDistanceY);
		this.mGenerals[0].setPosition(mGenerals[0].getX(), mGenerals[0].getY()
				- pDistanceY);
		backgroundSplite.setPosition(backgroundSplite.getX(),
				backgroundSplite.getY() - pDistanceY);

		play.setPosition(play.getX(), play.getY() - pDistanceY);

		contain_gold.setPosition(contain_gold.getX(), contain_gold.getY()
				- pDistanceY);

		select_item.setPosition(select_item.getX(), select_item.getY()
				- pDistanceY);
		select_skill.setPosition(select_skill.getX(), select_skill.getY()
				- pDistanceY);

		background_equipment.setPosition(background_equipment.getX(),
				background_equipment.getY() - pDistanceY);

		contain_select.setPosition(contain_select.getX(), contain_select.getY()
				- pDistanceY);

		taytuykinh.setPosition(taytuykinh.getX(), taytuykinh.getY()
				- pDistanceY);

		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		for (int i = 0; i < 4; i++) {
			contain[i].setPosition(contain[i].getX(), contain[i].getY()
					- pDistanceY);
		}
		MySprite sprite;
		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			ItemMenu item_menu = mListItemMenu[i];
			item_menu.setPosition(item_menu.getX(), item_menu.getY()
					- pDistanceY);
			item_menu.setpY(item_menu.getpY() - pDistanceY);

			sprite = mContainItemList[i];
			sprite.setPosition(sprite.getX(), sprite.getY() - pDistanceY);
			sprite.setpY(sprite.getpY() - pDistanceY);

			sprite = mListLockItemList[i];
			sprite.setPosition(sprite.getX(), sprite.getY() - pDistanceY);
			sprite.setpY(sprite.getpY() - pDistanceY);
		}

		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			SkillMenu skill_menu = mListSkillMenu[i];
			skill_menu.yPos = skill_menu.yPos - pDistanceY;
			skill_menu.setpY(skill_menu.getpY() - pDistanceY);

			sprite = mContainSkillList[i];
			sprite.yPos = sprite.yPos - pDistanceY;
			sprite.setpY(sprite.getpY() - pDistanceY);

			sprite = mListLockSkillList[i];
			sprite.yPos = sprite.yPos - pDistanceY;
			sprite.setpY(sprite.getpY() - pDistanceY);
		}

		for (int i = 0; i < contain.length; i++) {
			if (contain[i].isContainSkill()) {
				mListSkillMenu[contain[i].getIdSkill()].setPosition(
						contain[i].getX() + 5, contain[i].getY() + 5);
			}
		}

		// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (this.mCamera.getMinY() < 0) {
			this.mCamera.offsetCenter(0, 0);
			mCamera_CurentY = 0;
		}
	}

	private void scrollItemBox(final float pDistanceX, final float pDistanceY) {
		if (isInforScene)
			return;
		if (isAcceptMoveItem) {
			return;
		} else if (isMoveItemToUse
				&& !isAcceptMoveItem
				&& itemMoveable != -1
				&& mListItemMenu[itemMoveable].contains(xTouchMoveItem,
						yTouchMoveItem)
				&& !mListItemMenu[itemMoveable].isLock()) {
			if (Math.abs(pDistanceX) > Math.abs(pDistanceY) * 2) {
				isAcceptMoveItem = true;
				mListItemMenu[itemMoveable].setScale(1.5f);
				mListItemMenu[itemMoveable].setZIndex(5);
				return;
			}
		}
		if (((mCamera_CurentY - pDistanceY) < mCamera_MinY_ScrollItem)) {
			return;
		} else if ((mCamera_CurentY - pDistanceY) > mCamera_MaxY_ScrollItem + 200) {
			return;
		}

		this.mCamera.offsetCenter(0, -pDistanceY);
		mCamera_CurentY -= pDistanceY;

		this.mGenerals[2].setPosition(mGenerals[2].getX(), mGenerals[2].getY()
				- pDistanceY);
		this.mGenerals[1].setPosition(mGenerals[1].getX(), mGenerals[1].getY()
				- pDistanceY);
		this.mGenerals[0].setPosition(mGenerals[0].getX(), mGenerals[0].getY()
				- pDistanceY);
		backgroundSplite.setPosition(backgroundSplite.getX(),
				backgroundSplite.getY() - pDistanceY);

		play.setPosition(play.getX(), play.getY() - pDistanceY);

		contain_gold.setPosition(contain_gold.getX(), contain_gold.getY()
				- pDistanceY);

		select_item.setPosition(select_item.getX(), select_item.getY()
				- pDistanceY);
		select_skill.setPosition(select_skill.getX(), select_skill.getY()
				- pDistanceY);

		background_equipment.setPosition(background_equipment.getX(),
				background_equipment.getY() - pDistanceY);

		contain_select.setPosition(contain_select.getX(), contain_select.getY()
				- pDistanceY);
		contain_index.setPosition(contain_index.getX(), contain_index.getY()
				- pDistanceY);

		taytuykinh.setPosition(taytuykinh.getX(), taytuykinh.getY()
				- pDistanceY);

		// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		for (int i = 0; i < 4; i++) {
			contain[i].setPosition(contain[i].getX(), contain[i].getY()
					- pDistanceY);
		}

		MySprite sprite;
		for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
			SkillMenu skill_menu = mListSkillMenu[i];
			skill_menu.setPosition(skill_menu.getX(), skill_menu.getY()
					- pDistanceY);
			skill_menu.yPos = skill_menu.yPos - pDistanceY;
			skill_menu.setpY(skill_menu.getpY() - pDistanceY);

			sprite = mContainSkillList[i];
			sprite.setPosition(sprite.getX(), sprite.getY() - pDistanceY);
			sprite.yPos = sprite.yPos - pDistanceY;
			sprite.setpY(sprite.getpY() - pDistanceY);

			sprite = mListLockSkillList[i];
			sprite.setPosition(sprite.getX(), sprite.getY() - pDistanceY);
			sprite.yPos = sprite.yPos - pDistanceY;
			sprite.setpY(sprite.getpY() - pDistanceY);
		}

		for (int i = 0; i < 4; i++) {
			if (contain[i].isContainItem()) {
				mListItemMenu[contain[i].getIdItem() - totalSkill].setPosition(
						contain[i].getX() + 5, contain[i].getY() + 5);
			}
		}

		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			ItemMenu item_menu = mListItemMenu[i];
			item_menu.setpY(item_menu.getpY() - pDistanceY);

			sprite = mContainItemList[i];
			sprite.setpY(sprite.getpY() - pDistanceY);

			sprite = mListLockItemList[i];
			sprite.setpY(sprite.getpY() - pDistanceY);
		}

		for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
			MySprite item_menu = mContainItemList[i];
			item_menu.setpY(item_menu.getpY() - pDistanceY);
		}

		// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if (this.mCamera.getMinY() < 0) {
			this.mCamera.offsetCenter(0, 0);
			mCamera_CurentY = 0;
		}
	}

	private void scrollGeneralList(boolean isUP, final float pDistanceX,
			final float pDistanceY) {
		if (isInforScene)
			return;
		if (!isUP) {
			if (((mCamera_CurentX - pDistanceX) < mCamera_MinX)) {
				return;
			} else if ((mCamera_CurentX - pDistanceX) > 550) {
				return;
			}

			this.mCamera.offsetCenter(-pDistanceX, 0);
			mCamera_CurentX -= pDistanceX;

			if (pDistanceX < 0) {
				scrollLeft.setAlpha(1.0f);
				scrollRight.setAlpha(0.5f);
			} else if (pDistanceX >= 0) {
				scrollLeft.setAlpha(0.5f);
				scrollRight.setAlpha(1.0f);
			}

			backgroundSplite.setPosition(backgroundSplite.getX() - pDistanceX,
					backgroundSplite.getY());

			play.setPosition(play.getX() - pDistanceX, play.getY());

			contain_gold.setPosition(contain_gold.getX() - pDistanceX,
					contain_gold.getY());

			select_skill.setPosition(select_skill.getX() - pDistanceX,
					select_skill.getY());
			select_item.setPosition(select_item.getX() - pDistanceX,
					select_item.getY());

			taytuykinh.setPosition(taytuykinh.getX() - pDistanceX,
					taytuykinh.getY());

			contain_index.setPosition(contain_index.getX() - pDistanceX,
					contain_index.getY());

			// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			MySprite sprite;
			for (int i = 0; i < Constants.TOTAL_SKILL; i++) {
				SkillMenu skill_menu = mListSkillMenu[i];
				skill_menu.setPosition(skill_menu.getX() - pDistanceX,
						skill_menu.getY());
				skill_menu.xPos = skill_menu.xPos - pDistanceX;
				skill_menu.setpX(skill_menu.getpX() - pDistanceX);

				sprite = mContainSkillList[i];
				sprite.setPosition(sprite.getX() - pDistanceX, sprite.getY());
				sprite.xPos = sprite.xPos - pDistanceX;
				sprite.setpX(sprite.getpX() - pDistanceX);

				sprite = mListLockSkillList[i];
				sprite.setPosition(sprite.getX() - pDistanceX, sprite.getY());
				sprite.xPos = sprite.xPos - pDistanceX;
				sprite.setpX(sprite.getpX() - pDistanceX);
			}

			for (int i = 0; i < Constants.TOTAL_ITEM; i++) {
				ItemMenu item_menu = mListItemMenu[i];
				item_menu.setPosition(item_menu.getX() - pDistanceX,
						item_menu.getY());
				item_menu.xPos = item_menu.xPos - pDistanceX;
				item_menu.setpX(item_menu.getpX() - pDistanceX);

				sprite = mContainItemList[i];
				sprite.setPosition(sprite.getX() - pDistanceX, sprite.getY());
				sprite.xPos = sprite.xPos - pDistanceX;
				sprite.setpX(sprite.getpX() - pDistanceX);

				sprite = mListLockItemList[i];
				sprite.setPosition(sprite.getX() - pDistanceX, sprite.getY());
				sprite.xPos = sprite.xPos - pDistanceX;
				sprite.setpX(sprite.getpX() - pDistanceX);
			}

			for (int i = 0; i < 4; i++) {
				contain[i].setPosition(contain[i].getX() - pDistanceX,
						contain[i].getY());
			}

			// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

			background_equipment.setPosition(background_equipment.getX()
					- pDistanceX, background_equipment.getY());

			contain_select.setPosition(contain_select.getX() - pDistanceX,
					contain_select.getY());

		} else {
			int isScroll = checkGeneralUsed();
			if (isScroll != generalUse) {
				useGeneral.setVisible(true);
				try {
					useGeneral.setText("Chưa đủ điều kiện gọi\r\n tướng "
							+ Constants.GENERAL_NAME[isScroll]);
				} catch (Exception e) {
				}

				Timer time = new Timer();
				time.schedule(new TimerTask() {

					@Override
					public void run() {
						useGeneral.setVisible(false);

					}
				}, 2000);
			}

			if (generalUse == Constants.DICHHUTONG) {
				mGenerals[0].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[0].getX(), backgroundSplite.getX()));
				mGenerals[1].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[1].getX(), backgroundSplite.getX()
								+ mCaoLoTextureRegion.getWidth()));
				mGenerals[2].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[2].getX(), backgroundSplite.getX() + 2
								* mCaoLoTextureRegion.getWidth()));
				this.mCamera_CurentX = 0;
			} else if (generalUse == Constants.CAOLO) {
				mGenerals[0].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[0].getX(), backgroundSplite.getX()
								- mCaoLoTextureRegion.getWidth()));
				mGenerals[1].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[1].getX(), backgroundSplite.getX()));
				mGenerals[2].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[2].getX(), backgroundSplite.getX()
								+ mCaoLoTextureRegion.getWidth()));
				this.mCamera_CurentX = backgroundSplite.getWidth();
			} else if (generalUse == Constants.ANDUONGVUONG) {
				mGenerals[0].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[0].getX(), backgroundSplite.getX() - 2
								* mCaoLoTextureRegion.getWidth()));
				mGenerals[1].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[1].getX(), backgroundSplite.getX()
								- mCaoLoTextureRegion.getWidth()));
				mGenerals[2].registerEntityModifier(new MoveXModifier(0.1f,
						mGenerals[2].getX(), backgroundSplite.getX()));
				this.mCamera_CurentX = 2 * backgroundSplite.getWidth();
			}

			isGeneralScroll = false;
		}

	}

	// private int mNextGeneral = 1;
	// private int mPrivous = 0;
	//
	// private void onChangeGeneral(final int scroll) {
	// if (scroll == SCROLL_LEFT) {
	// int nextGeneral = mNextGeneral;
	//
	// boolean isReLoad = reLoadGeneral(nextGeneral);
	//
	// if (isReLoad) {
	// generalUse = nextGeneral;
	// gameStore.updateGeneralLastUsed(generalUse);
	// generalStore = gameStore.getGeneral(generalUse);
	// reLoadGeneralInfo(isReLoad);
	// reLoadShop();
	// }
	//
	// } else {
	//
	// }
	// }

	private int checkGeneralUsed() {
		float focus = backgroundSplite.getX()
				+ mBackgroundSpliteGeneralTextureRegion.getWidth() / 2;

		float focus_dichHuTong = mGenerals[0].getX()
				+ mDichHuTongTextureRegion.getWidth() / 2;
		float focus_caoLo = mGenerals[1].getX()
				+ mCaoLoTextureRegion.getWidth() / 2;
		float focus_anDuongVuong = mGenerals[2].getX()
				+ mAnDuongVuongTextureRegion.getWidth() / 2;

		float distance1 = Math.abs(focus - focus_dichHuTong);
		float distance2 = Math.abs(focus - focus_caoLo);
		float distance3 = Math.abs(focus - focus_anDuongVuong);

		float min = distance1;
		int temp = Constants.DICHHUTONG;

		if (min > distance2) {
			min = distance2;
			temp = Constants.CAOLO;
			if (min > distance3) {
				min = distance3;
				temp = Constants.ANDUONGVUONG;
			}
		} else if (min > distance3) {
			min = distance3;
			temp = Constants.ANDUONGVUONG;
		}

		boolean isReLoad = reLoadGeneral(temp);

		if (isReLoad) {
			generalUse = temp;
			gameStore.updateGeneralLastUsed(generalUse);
			generalStore = gameStore.getGeneral(generalUse);
			reLoadGeneralInfo(isReLoad);
			reLoadShop();
		}
		return temp;
	}

	// =========================================================================================================================//
	// MAINSCENE
	// =========================================================================================================================//

	private Sprite continueSprite;
	private Sprite replaySprite;
	private Sprite exitSprite;
	private Sprite pauseBGSprite;

	private void onLoadPauseGameScene() {
		pauseGameScene = new CameraScene(this.mCamera);

		pauseBGSprite = new Sprite(180, 70, mPauseBGTextureRegion);
		replaySprite = new Sprite(56, 221, mReplayTextureRegion);
		continueSprite = new Sprite(200, 220, mContinueTextureRegion);
		exitSprite = new Sprite(381, 225, mExitPauseTextureRegion);

		pauseGameScene.attachChild(pauseBGSprite);
		pauseBGSprite.attachChild(replaySprite);
		pauseBGSprite.attachChild(continueSprite);
		pauseBGSprite.attachChild(exitSprite);
		pauseGameScene.setBackgroundEnabled(false);

	}

	private void onLoadMainGameScene() {
		this.mArrowsList = new ArrayList<Arrow>();
		mArrowCoolDown = new CoolDown();
		mISkillUse = new ArrayList<AnimatedSkill>();
		mMagicsList = new ArrayList<Sprite>();
		this.mSoundCircleList = new ArrayList<SoundCircle>();
		this.mEnemyList = new ArrayList<Enemy>();
		this.mArrowOfRangeList = new ArrayList<EnemyArrow>();

		this.mMainScene = new MyScene();

		onLoadPauseGameScene();

		background = new Sprite(0, 0, mBackgroundTRegion);

		crossBow = new Sprite(0, 0, this.mCrossBowTRegion[0]);

		arrowFreeze = new Sprite(0.0F, 0.0f, this.mArrowsTRegion[0]);
		arrowFreeze.setPosition(-40.0f, 193.0f);

		citywall = new Sprite(7, 0, citywall_emergencyTextureRegion);
		citywall.setVisible(false);

		this.xTouch = (mCameraWidth + arrowFreeze.getX());
		this.yTouch = arrowFreeze.getY();

		onLoadMainGameHUD();
		onLoadResultScene();

		mMainScene.attachChild(background);
		mMainScene.attachChild(citywall);
		background.setZIndex(0);
		crossBow.setZIndex(0);
		arrowFreeze.setZIndex(0);
		mMainScene.attachChild(crossBow);
		mMainScene.attachChild(arrowFreeze);

		mGeneralList = new General[3];

		for (int i = 0; i < 3; i++) {
			if (i == Constants.DICHHUTONG) {
				mGeneralList[i] = new DichHuTong(i);
			} else if (i == Constants.CAOLO) {
				mGeneralList[i] = new CaoLo(i);
			} else if (i == Constants.ANDUONGVUONG) {
				mGeneralList[i] = new AnDuongVuong(i);
			}
		}

		mMainScene.setOnSceneTouchListener(this);
		mMainScene.setTouchAreaBindingEnabled(true);
		mMainScene.setOnSceneTouchListenerBindingEnabled(true);

	}

	private void onLoadMainGameHUD() {

		pause_button = new Sprite(10, -100, pauseButtonGameRegion);
		mStageText = new ChangeableText(370, 0, mFontViet1, "",
				"stage XXX".length());
		mCoinText = new ChangeableText(200, 3, mFontViet1, "",
				"xxxxxxxxxxx  ".length());
		mBloodText = new ChangeableText(70, -22, mFontViet1, "xxxxxxxxx",
				"xxxxxxxxxxxx".length());
		mManaText = new ChangeableText(70, -16, mFontViet1, "xxxxxxxxxx",
				"xxxxxxxxxxxx".length());

		face_general = new Sprite(-250, 360, this.faceGeneralTextureRegion);

		face_enemyGeneral = new Sprite(215, -20, faceEnemyGeneralTextureRegion);

		mSnailCoin = new Sprite(140, 5, mSnailCoinIcon);

		contain_blood = new Sprite(-260, 444, this.containRegion);

		contain_mana = new Sprite(-260, 460, this.containRegion);

		contain_enemy = new Sprite(800, 20, this.contain_enemyRegion);

		blood = new Sprite(0.0F, 0.0F, this.bloodRegion);
		blood.setScaleCenter(0, 0);
		blood.setScaleX(32.0f);

		mana = new Sprite(0, 0, this.manaRegion);
		mana.setScaleCenter(0.0f, 0.0f);
		mana.setScaleX(32.0f);

		magic_circle = new Sprite(0, 0, this.mMagic_circle);
		magic_circle.setPosition(mCameraWidth, mCameraHeight);
		magic_circle.setVisible(false);

		hud.attachChild(magic_circle);
		hud.attachChild(contain_blood);
		hud.attachChild(contain_mana);
		hud.attachChild(contain_enemy);
		hud.attachChild(face_general);
		hud.attachChild(pause_button);
		contain_enemy.attachChild(face_enemyGeneral);
		contain_mana.attachChild(mana);
		contain_blood.attachChild(blood);
		pause_button.attachChild(mStageText);
		pause_button.attachChild(mSnailCoin);
		pause_button.attachChild(mCoinText);
		contain_mana.attachChild(mManaText);
		contain_blood.attachChild(mBloodText);

		mSkillButton = new MySkillButton[3];
		for (int i = 0; i < 3; i++) {
			mSkillButton[i] = new MySkillButton(708 - 97 * i, 480,
					mIconSkillListTextureRegion[2].deepCopy());

			mSkillButton[i].setMask(mMaskIconSkillTextureRegion.deepCopy());
			mSkillButton[i].setPlus(mPlusIconSkillTextureRegion.deepCopy());
			mSkillButton[i].setLightCircle(mBrightIconSkillTextureRegion
					.deepCopy());

			hud.attachChild(mSkillButton[i]);
			mSkillButton[i].setVisible(false);
		}

		mCoinText.setVisible(false);
		mManaText.setVisible(false);
		mBloodText.setVisible(false);
		mSnailCoin.setVisible(false);
		mStageText.setVisible(false);
		contain_blood.setVisible(false);
		contain_mana.setVisible(false);
		contain_enemy.setVisible(false);
		face_enemyGeneral.setVisible(false);
		mana.setVisible(false);
		blood.setVisible(false);
		face_general.setVisible(false);
		pause_button.setVisible(false);
	}

	private void onShowGameHUD() {

		mCoinText.setVisible(true);
		mManaText.setVisible(true);
		mBloodText.setVisible(true);
		mSnailCoin.setVisible(true);
		mStageText.setVisible(true);
		contain_blood.setVisible(true);
		contain_mana.setVisible(true);
		contain_enemy.setVisible(true);
		face_enemyGeneral.setVisible(true);
		mana.setVisible(true);
		blood.setVisible(true);
		face_general.setVisible(true);
		pause_button.setVisible(true);

		float duration = 0.5f;

		for (int i = 0; i < 3; i++) {
			MoveYModifier move = new MoveYModifier(duration, 480, 383);
			move.setRemoveWhenFinished(true);
			mSkillButton[i].registerEntityModifier(move);
			mSkillButton[i].setVisible(true);
		}

		MoveXModifier move1 = new MoveXModifier(duration, -260, 70);
		move1.setRemoveWhenFinished(true);
		contain_blood.registerEntityModifier(move1.deepCopy());
		contain_mana.registerEntityModifier(move1);

		MoveXModifier move4 = new MoveXModifier(duration, 800, 525);
		move4.setRemoveWhenFinished(true);

		contain_enemy.registerEntityModifier(move4);

		MoveXModifier move2 = new MoveXModifier(duration, -250, 0);
		move2.setRemoveWhenFinished(true);
		face_general.registerEntityModifier(move2);

		MoveYModifier move3 = new MoveYModifier(duration, -100, 10);
		move3.setRemoveWhenFinished(true);
		pause_button.registerEntityModifier(move3);
	}

	private void unShowGameHUD() {
		for (int i = 0; i < 3; i++) {
			mSkillButton[i].setVisible(false);
			mSkillButton[i].setInitialPosition();
		}

		contain_blood.setInitialPosition();
		contain_mana.setInitialPosition();
		contain_blood.setVisible(false);
		contain_mana.setVisible(false);

		mCoinText.setVisible(false);
		mManaText.setVisible(false);
		mBloodText.setVisible(false);
		mSnailCoin.setVisible(false);
		mStageText.setVisible(false);
		face_enemyGeneral.setVisible(false);
		mana.setVisible(false);
		blood.setVisible(false);

		contain_enemy.setInitialPosition();
		contain_enemy.setVisible(false);

		face_general.setInitialPosition();
		face_general.setVisible(false);

		pause_button.setInitialPosition();
		pause_button.setVisible(false);
	}

	private void setMainGameScene() {
		mCamera.setCenter(mCameraWidth / 2, mCameraHeight / 2);

		mCoinText.setText("" + String.valueOf(0));

		mGameStates = GameStates.GAME_PLAY;
		isLockMainScene = true;

		isFissured = false;
		isMainGameScene = true;
		isAccountScene = false;
		isPause = false;

		face_enemyGeneral.setInitialPosition();

		citywall.setVisible(false);

		text.setVisible(false);

		mEngine.setScene(mMainScene);

		this.mMainScene.sortChildren();

		if (!mBackgroundMusic.isPlaying())
			mBackgroundMusic.play();
		if (mMenuMusic.isPlaying())
			mMenuMusic.pause();

		onLoadGeneral();
		onLoadGamePlay();

		mManaText
				.setText(String.valueOf((int) (generalStore.getIntelligent() * 10 + 50)));
		mBloodText
				.setText(String.valueOf((int) (generalStore.getStreng() * 25 + 100)));
		onShowGameHUD();
		
//		QplayAchievementUserInfo.getInstance(this, this).onStartGame();
	}

	private void onLoadGamePlay() {

		initGeneral();

		mStageText.setText("Hồi " + String.valueOf((stage) + 1));

		getTotalGameTime();

		useSkill();

		this.mMainScene.registerUpdateHandler(updateArrayList);
		this.mMainScene.registerUpdateHandler(updateHuman);
		this.mMainScene.registerUpdateHandler(attack);
		this.mMainScene.registerUpdateHandler(callEnemy);
	}

	private void useSkill() {
		useArrowSkill = -1;
		buttonArrow = -1;
		useManaArrowSkill = 0;
		for (int i = 1; i < 4; i++) {
			if (contain[i].isContainSkill()) {
				int id = contain[i].getIdSkill();
				SkillMenu skill = mListSkillMenu[id];
				mSkillButton[i - 1].used(true);

				mSkillButton[i - 1].setIdSkill(id);
				mSkillButton[i - 1].setLevel(skill.getLevel());
				mSkillButton[i - 1].setDelay(skill.getCoolDown());
				mSkillButton[i - 1].setState(skill.getState());
				mSkillButton[i - 1].setUseMana(skill.getUseMana());
				mSkillButton[i - 1].setDamage(skill.getDamage());

				mSkillButton[i - 1].setDelayEnemy(skill.getDelayEnemy());

				mSkillButton[i - 1].updateTextureRegion(
						mIconSkillListTextureRegion[id], true);

				idSkillUse[i - 1] = mListSkillMenu[contain[i].getIdSkill()]
						.getID();
				nameSkillUse[i - 1] = mListSkillMenu[contain[i].getIdSkill()]
						.getName();

				if (id % 2 == 0) {
					useArrowSkill = id;
					buttonArrow = i - 1;
					useManaArrowSkill = mSkillButton[i - 1].getUseMana();
				} else {
					mSkillButton[i - 1].start();
				}
			} else {
				mSkillButton[i - 1].setIdSkill(-1);
				mSkillButton[i - 1].used(false);
				mSkillButton[i - 1].resetInfo();
			}
		}
	}

	private void initGeneral() {
		increaseByItem();
		GENERAL_MANA = mGeneral.getManaPoints();
		GENERAL_HP = mGeneral.getHP();
	}

	private void detackMainGameScene() {

		MainGame.this.mMainScene.clearUpdateHandlers();
		MainGame.this.mMainScene.clearEntityModifiers();
		MainGame.this.mMainScene.clearChildScene();

		clearMainScene();

		holder.clearEntityModifiers();
		holder.setVisible(false);
		isHold = false;
		isSkill = false;

		unShowGameHUD();

		try {
			mBackgroundMusic.pause();
		} catch (Exception e) {
		}
		isPause = false;
//		QplayAchievementUserInfo.getInstance(this, this).onStopGame();
	}

	private void onLoadCrossBow(String name, int index) {
		crossBow.updateTextureRegion(mCrossBowTRegion[index].deepCopy(), true);
		arrowFreeze.updateTextureRegion(mArrowsTRegion[index].deepCopy());
		mArrows.resetTextureRegion(mArrowsTRegion[index].deepCopy());

		if (index != 1) {
			crossBow.setPosition(-30.0f, 115);
			arrowFreeze.setPosition(-30, 189);
			crossBow.setRotationCenter(50, 85);
			arrowFreeze.setRotationCenter(50, 8);
		} else {
			crossBow.setPosition(-20.0f, 115);
			arrowFreeze.setPosition(-40, 189);
			crossBow.setRotationCenter(40, 85);
			arrowFreeze.setRotationCenter(60, 8);
		}

		crossBow.setRotation(0);
		arrowFreeze.setRotation(0);
	}

	private void onLoadItemSelected() {
		totalArrow = 1;
		for (int i = 0; i < 4; i++) {
			if (contain[i].getKindOfEquipmentItem() == Constants.ITEM_NO) {
				crossBow_index = contain[i].getIdItem() - Constants.TOTAL_SKILL;
				crossBowName = Name_Shop[crossBow_index + Constants.TOTAL_SKILL];
				totalArrow += mListItemMenu[crossBow_index].getUpArrow();
			}
		}
	}

	private boolean reLoadGeneral(int temp) {

		if (temp >= gameStore.getmGeneralOpened() || temp == -1)
			return false;

		generalStore = gameStore.getGeneral(temp);

		return true;
	}

	private void resetPositionItem() {
		ItemMenu item;
		for (int i = 0; i < totalItem; i++) {
			item = mListItemMenu[i];
			item.setPosition(item.xPos, item.yPos);
			item.resetZIndex();
		}
	}

	private void loadShopElement() {
		int level = generalStore.getLevel();
		/*
		 * Item
		 */
		ItemMenu item;
		for (int i = 0; i < totalItem; i++) {
			item = mListItemMenu[i];
			item.setVisible(true);
			if (ID_Item_List_Store[i] != -1) {
				mListLockItemList[i].setVisible(false);
				item.setLock(false);
				item.setUnlock(true);
			} else {
				if (item.getLimit() > level) {
					item.setLock(true);
					item.setUnlock(false);
					mListLockItemList[i].setVisible(true);
					mListLockItemList[i].setTextureRegion(mLockMenu);
				} else {
					item.setLock(true);
					item.setUnlock(true);
					mListLockItemList[i].setVisible(true);
					mListLockItemList[i].setTextureRegion(mUnLockMenu);
				}
			}
		}

		for (int i = 0; i < 4; i++) {
			if (ID_Item_Use[i] != -1) {
				item = mListItemMenu[ID_Item_Use[i] - Constants.TOTAL_SKILL];

				if (item.getLimit() > level) {

					contain[i].setContainItem(false);
					contain[i].setIdItem(-1);
					contain[i].setKindOfEquipmentItem(-1);

					item.setPosition(item.xPos, item.yPos);
					item.setpX(item.xPos);
					item.setpY(item.yPos);

					item.setContainBy(-1);
					item.setZIndex(1);

					mEquipmentScene.sortChildren();

					gameStore.removeItemUsed(i);

				} else {

					item.setpX(contain[i].getX() + 5);
					item.setpY(contain[i].getY() + 5);
					item.setPosition(contain[i].getX() + 5,
							contain[i].getY() + 5);

					item.setZIndex(5);
					mEquipmentScene.sortChildren();

					contain[i].setKindOfEquipmentItem(item.kindOfEquipment);
					contain[i].setContainItem(true);
					contain[i].setIdItem(item.getID());
					item.setContainBy(i);
				}
			}
		}

		/*
		 * Skill
		 */
		SkillMenu skill;

		for (int i = 0; i < totalSkill; i++) {
			skill = mListSkillMenu[i];

			int temp = ID_Skill_Store[i];
			if (temp != -1) {
				mListLockSkillList[i].setVisible(false);
				skill.setLock(false);
				skill.setUnlock(true);
				if (temp == generalUse) {
					skill.setVisible(true);
				} else {
					skill.setVisible(false);
				}

			} else {
				skill.setLevel(1);
				skill.setVisible(true);
				mListLockSkillList[i].setVisible(true);
				if (skill.getLimit() > level) {
					skill.setLock(true);
					skill.setUnlock(false);
					mListLockSkillList[i].setTextureRegion(mLockMenu);
				} else {
					skill.setLock(true);
					skill.setUnlock(true);
					mListLockSkillList[i].setTextureRegion(mUnLockMenu);
				}
			}
		}

		for (int i = 0; i < 3; i++) {
			if (ID_Skill_Use[i] != -1) {
				skill = mListSkillMenu[ID_Skill_Use[i]];
				skill.setLevel(generalStore.getLevelSkillUsed(i));
				skill.setContainBy(i + 1);

				skill.setpX(contain[i + 1].getX() + 5);
				skill.setpY(contain[i + 1].getY() + 5);
				skill.setPosition(contain[i + 1].getX() + 5,
						contain[i + 1].getY() + 5);

				skill.setZIndex(5);
				mEquipmentScene.sortChildren();

				contain[i + 1].setContainSkill(true);
				contain[i + 1].setIdSkill(skill.getID());
				contain[i + 1].setState(skill.getState());
			}
		}

		if (isItemMenu) {
			for (int i = 0; i < totalItem; i++) {
				item = mListItemMenu[i];
				item.setVisible(true);

				if (item.isLock()) {
					mListLockItemList[i].setVisible(true);
				} else
					mListLockItemList[i].setVisible(false);
			}

			for (int i = 0; i < totalSkill; i++) {
				skill = mListSkillMenu[i];
				skill.setVisible(false);
				mListLockSkillList[i].setVisible(false);
			}

			select_item.setCurrentTileIndex(1);
			select_skill.setCurrentTileIndex(0);
			taytuykinh.setVisible(false);
		} else {
			for (int i = 0; i < totalItem; i++) {
				mListItemMenu[i].setVisible(false);
				mListLockItemList[i].setVisible(false);
			}

			for (int i = 0; i < totalSkill; i++) {
				skill = mListSkillMenu[i];

				if (skill.isLock()) {
					mListLockSkillList[i].setVisible(true);
				} else
					mListLockSkillList[i].setVisible(false);
			}
			select_item.setCurrentTileIndex(0);
			select_skill.setCurrentTileIndex(1);
			taytuykinh.setVisible(true);
		}
	}

	private void reLoadShop() {
		resetContainMenu();
		resetPositionItem();

		onLoadSkillGeneralUsed();

		onLoadItemStore();

		onLoadGameItem();
		onLoadGeneralSkill();

		loadShopElement();
	}

	private void reLoadGeneralInfo(boolean isReLoad) {
		if (!isReLoad)
			return;
		int level = generalStore.getLevel();
		mHPGeneralUse.setText("Sinh lực        : "
				+ (generalStore.getStreng() * 25 + 100));
		mMPGeneralUse.setText("Năng lượng  : "
				+ (generalStore.getIntelligent() * 10 + 50));
		mEXPGeneralUse.setText("Kinh nghiệm: "
				+ (int) generalStore.getEXP() + "/"+EXP_LEVEL[level]);
		mLevelGeneral.setText("Cấp độ          : "
				+ level);
		mGeneralName.setText(""
				+ Constants.GENERAL_NAME[generalStore.getName()]);

		if (generalStore.getPointUpBasic() > 0)
			mWarningUpgrade.animate(200);
		else
			mWarningUpgrade.stopAnimation(0);
	}

	private void increaseByItem() {

		for (int i = 0; i < 4; i++) {
			if (contain[i].isContainItem()) {
				int index = contain[i].getIdItem() - Constants.TOTAL_SKILL;

				float upAttack = mListItemMenu[index].getAttack();
				float upDefend = mListItemMenu[index].getDefend();
				float upStreng = mListItemMenu[index].getUpStreng();
				float upIntel = mListItemMenu[index].getUpIntel();
				float upArrowVelocity = mListItemMenu[index]
						.getUpArrowVelocity();

				mGeneral.increaseAttack(upAttack);
				mGeneral.increaseDefend(upDefend);
				mGeneral.increaseIntel(upIntel);
				mGeneral.increaseStreng(upStreng);
				mGeneral.increaseArrowVelocity(upArrowVelocity);
			}
		}

		float factor = mGeneral.getAgility();

		if (factor > 100)
			factor = 100;

		DELAY_ARROW_TIME = 650 - (long) (factor * Constants.DELAY_FACTOR * (1 + mGeneral
				.getUpArrowVelocity() / 100));

		VELOCITY_ARROW = (0.8f + factor * 0.005f) * Constants.COEFFICIENT;

		mArrowCoolDown.setDelay(DELAY_ARROW_TIME);
	}

	private void onLoadGameStoreAccount() throws InvalidChecksumException {
		mGameSrotes = new GameStore[3];
		generalLastUsed = new int[3];
		for (int i = 0; i < 3; i++) {
			mGameSrotes[i] = new GameStore(this, i);
			generalLastUsed[i] = mGameSrotes[i].getGeneralLastUsed();
		}
	}

	private void onLoadGeneral() {
		generalStore = gameStore.getGeneral(generalUse);

		mGeneral = mGeneralList[generalUse];

		mGeneral.setIntelligent(this.generalStore.getIntelligent());
		mGeneral.setStreng(this.generalStore.getStreng());
		mGeneral.setAgility(this.generalStore.getAgility());
		mGeneral.setAttackBasic();

	}

	/*
	 * Main Process
	 */

	private BloodLine newBloodLine(final Enemy enemy) {
		BloodLine bloodLine = new BloodLine(enemy.getWidth() / 2 - 32, 0,
				mBloodPieceFrame, mBloodPiece);

		enemy.attachChild(bloodLine);

		bloodLine.total(enemy.getInitHP());

		return bloodLine;

	}

	private void updateBlood() {
		if (!CoolDownRecoverBlood.sharedCoolDown(1000).checkValidity())
			return;
		if (mGeneral.getHP() < GENERAL_HP && mGeneral.getHP() > 0) {
			mGeneral.recoverBlood();
			if (mGeneral.getHP() > GENERAL_HP)
				mGeneral.setHP(GENERAL_HP);
		}
	}

	public void updateMana() {
		if (!CoolDownRecoverMana.sharedCoolDown(1000).checkValidity())
			return;
		if (mGeneral.getManaPoints() < GENERAL_MANA) {
			mGeneral.recoverMana();
			if (mGeneral.getManaPoints() > GENERAL_MANA)
				mGeneral.setManaPoints(GENERAL_MANA);
		}
	}

	private void updateStatusEnemy() {
		countTimeGame = System.currentTimeMillis() - timeStartGame
				- totalPauseGame;
		if (mGeneral.getHP() <= 0 && !isPause) {
			isPause = true;
			gameOver();
			return;
		}
		if (countTimeGame > totalTimeCallEnemy && mEnemyList.isEmpty()
				&& mGeneral.getHP() > 0) {
			win();
			return;
		}

		else if (!mEnemyList.isEmpty() && mEngine.isRunning()) {
			Enemy enemy;
			synchronized (mEnemyList) {
				isDrum = false;
				isSpellFlying = false;
				isEnemyMove = false;
				isAurra = false;

				int i = 0;

				while (i < mEnemyList.size()) {
					if (!mEngine.isRunning())
						break;
					enemy = mEnemyList.get(i);
					if (!enemy.isListenSoundAurra() && isUpEnemy) {
						enemy.handler
								.setVelocityX(enemy.handler.getVelocityX() * 1.3f);
						enemy.setHP(enemy.getHP() * 1.3f);
						enemy.setAttackBasic(enemy.getAttackBasic() * 1.3f);
						enemy.setListenSoundAurra(true);
						// enemy.setArmour(enemy.getArmour() * 1.3f);
					}
					if (enemy.name == Constants.MELEE) {
						if (enemy.getStatus() == Constants.MOVE) {
							if (enemy.getX() <= Constants.XPOS_ATTACK_MELEE) {
								enemy.unregisterUpdateHandler(enemy.handler);
								enemy.setStatus(Constants.ATTACK);
								enemy.setmTextureRegion_next(mMeleeTRegion_Stab
										.deepCopy());
								enemy.allowChangeStatus(true);
							} else
								isEnemyMove = true;
						} else if (enemy.getStatus() == Constants.ATTACK
								&& !enemy.isAttack()
								&& enemy.getCurrentTileIndex() == 5) {
							if (!enemy.isListenSoundAurra() && isUpEnemy) {
								enemy.handler.setVelocityX(enemy.handler
										.getVelocityX() * 1.1f);
								enemy.setHP(enemy.getHP() * 1.1f);
								enemy.setAttackBasic(ATTACK_MELEE * 1.1f);
								enemy.setListenSoundAurra(true);
							}
							try {
								sSword.play();

							} catch (Exception e) {
							}
							mGeneral.reduceBlood(enemy.getAttackBasic());
							enemy.setAttack(true);

						}
						if (enemy.getHP() <= 0
								&& enemy.getCurrentTileIndex() == Constants.ENEMY_DIE_TILE_INDEX
								&& enemy.getAlpha() < 1) {
							enemy.setLife(false);
							enemy.clearUpdateHandlers();
							enemy.clearEntityModifiers();
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								continue;
							} catch (Exception e) {
							}
						}
					} else if (enemy.name == Constants.RANGE) {
						if (enemy.getStatus() == Constants.MOVE) {
							if (enemy.getX() <= Constants.XPOS_ATTACK_RANGE) {
								enemy.unregisterUpdateHandler(enemy.handler);
								enemy.setStatus(Constants.ATTACK);
								enemy.setmTextureRegion_next(mRangeTRegion_Fire
										.deepCopy());
								enemy.allowChangeStatus(true);
							} else
								isEnemyMove = true;

						} else if (enemy.getStatus() == Constants.ATTACK
								&& !enemy.isAttack()
								&& enemy.getCurrentTileIndex() == 7) {
							if (!enemy.isListenSoundAurra() && isUpEnemy) {
								enemy.handler.setVelocityX(enemy.handler
										.getVelocityX() * 1.1f);
								enemy.setHP(enemy.getHP() * 1.1f);
								enemy.setAttackBasic(ATTACK_MELEE * 1.1f);
								enemy.setListenSoundAurra(true);
							}
							arrowOfRange(enemy.getX(), enemy.getY() + 25);
							enemy.setAttack(true);
						}
						if (enemy.getHP() <= 0
								&& enemy.getCurrentTileIndex() == Constants.ENEMY_DIE_TILE_INDEX
								&& enemy.getAlpha() < 1) {
							enemy.setLife(false);
							enemy.clearUpdateHandlers();
							enemy.clearEntityModifiers();
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								continue;
							} catch (Exception e) {
							}
						}
					} else if (enemy.name == Constants.SPELL) {
						if (!isSpellFlying)
							isSpellFlying = true;
						if (enemy.getStatus() == Constants.MOVE) {
							if (enemy.getX() <= Constants.XPOS_ATTACK_SPELL) {
								enemy.handler.setEnabled(false);
								enemy.setStatus(Constants.ATTACK);
								enemy.allowChangeStatus(true);
							}
						} else if (enemy.getStatus() == Constants.ATTACK
								&& !enemy.isAttack()
								&& enemy.getCurrentTileIndex() == 7) {
							enemy.setAttack(true);
							magicOfSpell(enemy.getX() - 50, enemy.getY() + 25);
						}
						if (enemy.getHP() <= 0
								&& enemy.getCurrentTileIndex() == Constants.SPELL_DIE_TILE_INDEX
								&& enemy.getAlpha() < 1) {
							enemy.setLife(false);
							enemy.clearUpdateHandlers();
							enemy.clearEntityModifiers();
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								continue;
							} catch (Exception e) {
							}
						}
					} else if (enemy.name == Constants.AURRA) {
						if (!isDrum)
							isDrum = true;
						if (enemy.getStatus() == Constants.MOVE) {
							if (!isAurra)
								isAurra = true;
							if (enemy.getX() <= Constants.XPOS_STAND_AURRA) {
								enemy.handler.setEnabled(false);
								enemy.setStatus(Constants.ATTACK);
								enemy.allowChangeStatus(true);
							}
						} else if (enemy.getStatus() == Constants.ATTACK
								&& !enemy.isAttack()
								&& enemy.getCurrentTileIndex() == 3) {
							if (!isAurra)
								isAurra = true;
							enemy.setAttack(true);
							soundCircleOfAurra(enemy.getX() - 25,
									enemy.getY() + 40);
						}
						if (enemy.getHP() <= 0
								&& enemy.getCurrentTileIndex() == Constants.AURRA_DIE_TILE_INDEX
								&& enemy.getAlpha() < 1) {
							enemy.setLife(false);
							enemy.clearUpdateHandlers();
							enemy.clearEntityModifiers();
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								continue;
							} catch (Exception e) {
							}
						}
					} else if (enemy.name == Constants.TANK) {
						if (enemy.name == Constants.TANK) {
							if (enemy.getStatus() == Constants.MOVE) {
								if (enemy.getX() <= Constants.XPOS_ATTACK_TANK) {
									enemy.unregisterUpdateHandler(enemy.handler);
									enemy.setStatus(Constants.ATTACK);
									enemy.setmTextureRegion_next(mTankAttackTextureRegion
											.deepCopy());
									enemy.allowChangeStatus(true);
								}
							} else if (enemy.getStatus() == Constants.ATTACK
									&& !enemy.isAttack()
									&& enemy.getCurrentTileIndex() == 5) {
								if (!enemy.isListenSoundAurra() && isUpEnemy) {
									enemy.handler.setVelocityX(enemy.handler
											.getVelocityX() * 1.1f);
									enemy.setAttackBasic(ATTACK_MELEE * 1.1f);
									enemy.setListenSoundAurra(true);
								}
								try {
									sSword.play();
								} catch (Exception e) {
								}
								mGeneral.reduceBlood(enemy.getAttackBasic());
								enemy.setAttack(true);

							}
							if (enemy.getHP() <= 0
									&& enemy.getCurrentTileIndex() == Constants.ENEMY_DIE_TILE_INDEX
									&& enemy.getAlpha() < 1) {
								enemy.setLife(false);
								enemy.clearUpdateHandlers();
								enemy.clearEntityModifiers();
								try {
									removeEntity(enemy);
									mEnemyList.remove(i);
									continue;
								} catch (Exception e) {
								}
							}
						}
					} else if (enemy.name == Constants.NHAMNGAO) {
						if (((NhamNgao) enemy).getState() == NhamNgaoStates.MOVE) {
							if (((NhamNgao) enemy).getX() <= Constants.XPOS_ATTACK_NHAMNGAO) {
								((NhamNgao) enemy).allowChangeStatus(true);
								((NhamNgao) enemy).handler.setEnabled(false);
								((NhamNgao) enemy)
										.setLastState(NhamNgaoStates.MOVE);
								((NhamNgao) enemy)
										.setState(NhamNgaoStates.ATTACK);
								((NhamNgao) enemy).isAllowAttack = true;
//								Log.d("nhamngao", "move to attack" + " vitri "
//										+ enemy.getX() + "mau " + enemy.getHP());
							}
						} else if (((NhamNgao) enemy).getState() == NhamNgaoStates.ATTACK
								&& !((NhamNgao) enemy).isAttack()
								&& enemy.getCurrentTileIndex() == 0) {
							mGeneral.reduceBlood(((NhamNgao) enemy)
									.getAttackBasic());
							((NhamNgao) enemy).setAttack(true);
						}
						if (((NhamNgao) enemy).getCurrentTileIndex() == 16) {
							((NhamNgao) enemy).setLife(false);
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								continue;
							} catch (Exception e) {
							}
						}
					} else if (enemy.name == Constants.FLAT_DRAGON) {
						if (((FlatDragon) enemy).getState() == FlatDragonStates.MOVE) {
							if (enemy.getX() <= Constants.XPOS_FIRE_FLATDRAGON
									&& enemy.getX() > Constants.XPOS_FIRE_FLATDRAGON - 50
									&& ((FlatDragon) enemy).lastCheckFire + 5000 < System
											.currentTimeMillis()) {
								int r = random(0, 2);

								if (r != 2) {
									((FlatDragon) enemy).lastCheckFire = System
											.currentTimeMillis();
									((FlatDragon) enemy)
											.setState(FlatDragonStates.FIRE);
									enemy.allowChangeStatus(true);
								}

							} else if (enemy.getX() <= Constants.XPOS_BEAT_FLATDRAGON) {
								((FlatDragon) enemy)
										.setState(FlatDragonStates.BEAT);
								enemy.allowChangeStatus(true);
							}
						} else if (((FlatDragon) enemy).getState() == FlatDragonStates.FIRE
								&& enemy.getCurrentTileIndex() == 18
								&& !((FlatDragon) enemy).isFire()) {
							try {
								sDragonFireSkill.play();
							} catch (Exception e) {
								throw new IllegalAccessError();
							}
							fireDragon(enemy.getX(), enemy.getY(),
									((FlatDragon) enemy).getAttackBasic());
							((FlatDragon) enemy).setFireSkill(true);
						} else if (((FlatDragon) enemy).getState() == FlatDragonStates.BEAT
								&& enemy.getCurrentTileIndex() == 10
								&& !enemy.isAttack()) {
							try {
								sWallHit.play();
							} catch (Exception e) {
							}
							mGeneral.reduceBlood(((FlatDragon) enemy)
									.getAttackBasic());
							((FlatDragon) enemy).setAttack(true);
						} else if (((FlatDragon) enemy).getState() == FlatDragonStates.DIE
								&& ((FlatDragon) enemy).isLife()) {

							enemy.clearUpdateHandlers();
							enemy.clearEntityModifiers();
							enemy.setVisible(false);

							enemy.setLife(false);
							try {
								removeEntity(enemy);
								mEnemyList.remove(i);
								gameHandler.postDelayed(new Runnable() {

									@Override
									public void run() {
										final Text shout = new Text(200, 150,
												mFontVietTo,
												"Tao sẽ trở lại và ăn hại gấp đôi \n.a...a....a..........a");
										shout.setColor(0.8f, 0.6f, 0.5f);
										tableWinGame.attachChild(shout);
										gameHandler.postDelayed(new Runnable() {

											@Override
											public void run() {
												tableWinGame.detachChild(shout);
											}
										}, 1000);
									}
								}, 500);
								continue;

							} catch (Exception e) {
							}

						}
					} else if (enemy.name == Constants.DOTHU) {
						if (((DoThu) enemy).getState() == DoThuStates.RUN) {
							if (enemy.getX() <= Constants.XPOS_ATTACK_DOTHU) {
								enemy.allowChangeStatus(true);
								enemy.handler.setEnabled(false);
								((DoThu) enemy).isAttacted = false;
								((DoThu) enemy).isAllowAttack = true;
								((DoThu) enemy).setState(DoThuStates.ATTACK);
							}
						} else if (((DoThu) enemy).getState() == DoThuStates.ATTACK
								&& !((DoThu) enemy).isAttack()
								&& enemy.getCurrentTileIndex() == 10) {
							((DoThu) enemy).setAttack(true);
							doThuMagic(enemy.getX(), enemy.getY());

						} else if (((DoThu) enemy).getState() == DoThuStates.RUNAWAY) {
							if (enemy.getX() >= 900) {
								enemy.clearUpdateHandlers();
								enemy.clearEntityModifiers();
								try {
									mEnemyList.remove(i);
									removeEntity(enemy);
									continue;
								} catch (Exception e) {
								}
							}
						}
					}
					i++;
				}
			}
		}

		if (!mDrum.isPlaying() && isDrum) {
			mDrum.play();
		} else if (!isDrum && mDrum.isPlaying()) {
			mDrum.pause();
		}

		if (isSpellFlying && !mSpellFlying.isPlaying()) {
			mSpellFlying.play();
		} else if (!isSpellFlying && mSpellFlying.isPlaying()) {
			mSpellFlying.pause();
		}

		if (isEnemyMove && !mEnemyMove.isPlaying()) {
			mEnemyMove.play();
		} else if (!isEnemyMove && mEnemyMove.isPlaying()) {
			mEnemyMove.pause();
		}
	}

	private void createMinisterEnemy(int name) {
		switch (name) {
		case 0:
			nhamNgao();
			callMinisterEnemy[0] = -1;
			break;
		case 1:
			doThu();
			callMinisterEnemy[1] = -1;
			break;

		case 2:
			flatDragon();
			callMinisterEnemy[2] = -1;
			break;

		default:
			break;
		}
	}

	private void nhamNgao() {
		NhamNgao nhamNgao = new NhamNgao(7, 0, 0, mNhamNgaoMove.deepCopy(),
				mNhamNgaoAttack.deepCopy());

		float factor = 1;

		if (stage == Constants.STAGE_BOSS_NHAMNGAO_1) {
			factor = 1;
		} else if (stage == Constants.STAGE_BOSS_NHAMNGAO_2) {
			factor = 1.5f;
		} else if (stage == Constants.STAGE_BOSS_1) {
			factor = 2;
		} else if (stage == Constants.STAGE_BOSS_3) {
			factor = 2.5f;
		} else if (stage == Constants.STAGE_BOSS_4) {
			factor = 3;
		}

		nhamNgao.setStreng(Constants.NHAM_NGAO_STRENG * factor);
		nhamNgao.setAgility(Constants.NHAM_NGAO_AGILITY * factor);
		nhamNgao.setIntelligent(Constants.NHAM_NGAO_INTEL * factor);
		nhamNgao.setAttackBasic();
		nhamNgao.setCoolDownRecoverHP(1000);

		nhamNgao.setVelocity(-VELOCITY_X_NHAMNGAO * factor);

		float yPos = MathUtils.random(50, 300);

		nhamNgao.setPosition(800, yPos);

		mEnemyList.add(nhamNgao);
		mMainScene.attachChild(nhamNgao);
		try {
			nhamNgao.setZIndex(mEnemyList.size());
		} catch (Exception e) {
			nhamNgao.setZIndex(2);
		}
		mMainScene.sortChildren();

	}

	private void doThu() {
		if (mDoThuMagicPool == null)
			mDoThuMagicPool = new DoThuMagicPool(mDoThuSkillTextureRegion);
		if (mDoThuMagicList == null)
			mDoThuMagicList = new ArrayList<DoThuMagic>();

		float factor = 1;

		if (stage == Constants.STAGE_BOSS_DOTHU_1) {
			factor = 1;
		} else if (stage == Constants.STAGE_BOSS_DOTHU_2) {
			factor = 1.5f;
		} else if (stage == Constants.STAGE_BOSS_1) {
			factor = 2;
		} else if (stage == Constants.STAGE_BOSS_2) {
			factor = 2.5f;
		} else if (stage == Constants.STAGE_BOSS_4) {
			factor = 3;
		}

		float yPos = MathUtils.random(30, 300);

		DoThu mDoThu = new DoThu(10, 850, yPos, mDoThuTextureRegion.deepCopy());

		mDoThu.setStreng(Constants.DO_THU_STRENG * factor);
		mDoThu.setAgility(Constants.DO_THU_AGILITY * factor);
		mDoThu.setIntelligent(Constants.DO_THU_INTEL * factor);
		mDoThu.setCoolDownRecoverHP(1000);
		mDoThu.setAttackBasic();

		mDoThu.setVelocity(-Constants.VELOCITY_DOTHU_DEFAULT * factor);

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		addEnemy(mDoThu);
		try {
			mDoThu.setZIndex(mEnemyList.size());
		} catch (Exception e) {
			mDoThu.setZIndex(2);
		}
		mMainScene.sortChildren();
	}

	private void doThuMagic(final float pX, final float pY) {
		DoThuMagic magic = mDoThuMagicPool.obtainPoolItem();

		magic.setPosition(pX, pY);
		ScaleModifier modifier = new ScaleModifier(3.0f, 0.5f, 3.0f);
		AlphaModifier aModifier = new AlphaModifier(3.0f, 1.0f, 0.0f);
		magic.registerEntityModifier(modifier.deepCopy());
		magic.registerEntityModifier(aModifier.deepCopy());
		magic.beginUse();
		magic.setZIndex(mMainScene.getChildCount());

		try {
			sDoThuSkill.play();
		} catch (Exception e) {
		}

		mMainScene.attachChild(magic);
		this.mDoThuMagicList.add(magic);

		this.mMainScene.sortChildren();
	}

	private void flatDragon() {
		float yPos = MathUtils.random(80, 300);
		FlatDragon flatDragon = new FlatDragon(0, 800, yPos,
				mFlatDragonMoveTextureRegion.deepCopy(),
				mFlatDragonAttackTextureRegion.deepCopy());

		float factor = 1;

		if (stage == Constants.STAGE_BOSS_FLAT_DRAGON_1) {
			factor = 1;
		} else if (stage == Constants.STAGE_BOSS_FLAT_DRAGON_2) {
			factor = 1.5f;
		} else if (stage == Constants.STAGE_BOSS_2) {
			factor = 2;
		} else if (stage == Constants.STAGE_BOSS_3) {
			factor = 2.5f;
		} else if (stage == Constants.STAGE_BOSS_4) {
			factor = 3;
		}

		flatDragon.setStreng(Constants.FLAT_DRAGON_STRENG * factor);
		flatDragon.setAgility(Constants.FLAT_DRAGON_AGILITY * factor);
		flatDragon.setIntelligent(Constants.FLAT_DRAGON_INTEL * factor);

		flatDragon.setCoolDownRecoverHP(2000);

		flatDragon.setAttackBasic();

		flatDragon
				.setVelocity(-Constants.VELOCITY_FLAT_DRAGON_DEFAULT * factor);

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		addEnemy(flatDragon);
		try {
			flatDragon
					.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			flatDragon.setZIndex(5);
		}
		mMainScene.sortChildren();
	}

	private SkillDragon mFireDragon = null;

	private void fireDragon(final float pX, final float pY, final float attack) {
		if (mFireDragon == null) {
			mFireDragon = new SkillDragon(0, pX, pY,
					mSkillFireDragonTextureRegon);
			mMainScene.attachChildToHighest(mFireDragon);
		}

		mFireDragon.setVisible(true);
		mFireDragon.setZIndex(mMainScene.getChildCount());
		mFireDragon.activeFire(pX, pY);
		gameHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mGeneral.reduceBlood(attack);
			}
		}, 350);

	}

	private void magicOfSpell(float pX, float pY) {
		Sprite magic = mMagics.obtainPoolItem();
		magic.setPosition(pX, pY);
		MoveXModifier modifier = new MoveXModifier(1.0f, pX, 100);
		magic.registerEntityModifier(modifier.deepCopy());
		magic.setZIndex(mEnemyList.get(mEnemyList.size() - 1).getZIndex() + 1);
		mMainScene.attachChild(magic);
		this.mMagicsList.add(magic);
		this.mMainScene.sortChildren();

		sSpellAttack.play();
	}

	private void arrowOfRange(float pX, float pY) {
		EnemyArrow arrow = mArrowOfRange.obtainPoolItem();
		arrow.setPosition(pX, pY - 5);
		arrow.setZIndex(mEnemyList.get(mEnemyList.size() - 1).getZIndex() + 1);
		mMainScene.attachChild(arrow);
		this.mArrowOfRangeList.add(arrow);
		this.mMainScene.sortChildren();
	}

	private void soundCircleOfAurra(float pX, float pY) {
		SoundCircle newCircle = mCircles.obtainPoolItem();
		newCircle.setPosition(pX, pY);
		ScaleModifier modifier = new ScaleModifier(4.0f, 0.5f,
				Constants.ATTACK_AURRA_DEFAULT);
		AlphaModifier aModifier = new AlphaModifier(4.0f, 1.0f, 0.0f);
		newCircle.registerEntityModifier(modifier.deepCopy());
		newCircle.registerEntityModifier(aModifier.deepCopy());
		newCircle.setBegin();
		newCircle
				.setZIndex(mEnemyList.get(mEnemyList.size() - 1).getZIndex() + 1);
		mMainScene.attachChild(newCircle);
		this.mSoundCircleList.add(newCircle);
		this.mMainScene.sortChildren();
	}

	private void sortListEnemy() {
		synchronized (mEnemyList) {
			try {
				if (!mEnemyList.isEmpty()) {
					float k;
					int j;
					int size = mEnemyList.size();
					int minZIndex = mEnemyList.get(0).getZIndex();
					Enemy last;
					for (int i = 1; i < size && !isPause; i++) {
						last = mEnemyList.get(i);
						k = mEnemyList.get(i).getYSort();
						j = i;
						minZIndex = Math.min(minZIndex, last.getZIndex());
						while ((j > 0)
								&& (mEnemyList.get(j - 1).getYSort() > k)) {
							mEnemyList.set(j, mEnemyList.get(j - 1));
							j--;
						}
						mEnemyList.set(j, last);
					}
					for (Enemy e : mEnemyList) {
						e.setZIndex(minZIndex + mEnemyList.indexOf(e));
					}
					mMainScene.sortChildren();
				}
			} catch (Exception e) {
			}
		}
	}

	private Sprite hoaTien() {
		Sprite hoaTien = new Sprite(-60, -2,
				mSkillPassiveTextureRegion[0].deepCopy());

		return hoaTien;
	}

	private Sprite hanBangTien() {
		Sprite hanBangTien = new Sprite(-60, -2,
				mSkillPassiveTextureRegion[1].deepCopy());

		return hanBangTien;
	}

	private Sprite mocTien() {
		Sprite mocTien = new Sprite(-60, -2,
				mSkillPassiveTextureRegion[2].deepCopy());
		return mocTien;
	}

	private void shoot(final int id) {
		switch (totalArrow) {
		case 1:
			shoot1Arrow(id);
			break;
		case 2:
			shoot2Arrows(id);
			break;

		case 3:
			shoot3Arrows(id);
			break;

		default:
			break;
		}
	}

	private void shoot1Arrow(final int id) {
		if (!mArrowCoolDown.checkValidity())
			return;
		float xOffset = this.xTouch - arrowFreeze.getX()
				- this.arrowFreeze.getWidth() / 2;
		float yOffset = this.yTouch - arrowFreeze.getY();
		float degree = (float) (Math.toDegrees(Math.atan2(xOffset, yOffset)) - 90);

		Arrow arrow = mArrows.obtainPoolItem();
		arrow.setPosition(arrowFreeze.getX(), arrowFreeze.getY());

		this.mMainScene.attachChildZIndex(1, arrow);

		float ratio = yOffset / xOffset;
		float realX = this.mCamera.getWidth() + arrow.getWidth() / 2.0f;
		float realY = ratio * realX + arrow.getY();

		float offRealX = realX - arrow.getX();
		float offRealY = realY - arrow.getY();

		float offset = (float) Math.sqrt(offRealX * offRealX + offRealY
				* offRealY);

		arrow.setRotationCenter(arrowFreeze.getRotationCenterX(),
				arrowFreeze.getRotationCenterY());
		arrow.setRotation(-degree);
		arrowFreeze.setRotation(-degree);
		arrowFreeze.setVisible(false);

		float velocity = VELOCITY_ARROW;
		float realMoveDuration = offset / velocity;

		MoveModifier mod = new MoveModifier(realMoveDuration, arrow.getX(),
				realX, arrow.getY(), realY);
		arrow.registerEntityModifier(mod.deepCopy());

		if (id == 0) {
			arrow.attachChild(hoaTien());
			arrow.setDamage(mGeneral.getAttackBasic(), 0,
					mSkillButton[buttonArrow].getLevel());
		} else if (id == 2) {
			arrow.attachChild(hanBangTien());
			arrow.setDamage(mGeneral.getAttackBasic(), 2,
					mSkillButton[buttonArrow].getLevel());
		} else if (id == 4) {
			arrow.attachChild(mocTien());
			arrow.setDamage(mGeneral.getAttackBasic(), 4,
					mSkillButton[buttonArrow].getLevel());
		} else if (id == 6) {
			arrow.setDamage(mGeneral.getAttackBasic(), 6,
					mSkillButton[buttonArrow].getLevel());
		} else if (id == 8) {
			arrow.setDamage(mGeneral.getAttackBasic(), 8,
					mSkillButton[buttonArrow].getLevel());
		} else
			arrow.setDamage(mGeneral.getAttackBasic());

		mGeneral.useMana(useManaArrowSkill);

		this.mArrowsList.add(arrow);
		try {
			sArrowShoot.play();
		} catch (Exception e) {
		}
	}

	private void shoot2Arrows(final int id) {
		if (!mArrowCoolDown.checkValidity())
			return;

		float xOffset = this.xTouch - arrowFreeze.getX()
				- this.arrowFreeze.getWidth() / 2;
		float yOffset = this.yTouch - arrowFreeze.getY();
		float degree = (float) (Math.toDegrees(Math.atan2(xOffset, yOffset)) - 90);
		arrowFreeze.setRotation(-degree);
		arrowFreeze.setVisible(false);

		float dx = -TAN_2 * yOffset;
		float dy = TAN_2 * xOffset;

		for (int i = 0; i < 2; i++) {
			Arrow arrow = mArrows.obtainPoolItem();
			arrow.setPosition(arrowFreeze.getX(), arrowFreeze.getY());

			this.mMainScene.attachChildZIndex(1, arrow);

			float _xOffset = xOffset + (int) (Math.pow(-1, i)) * dx;
			float _yOffset = yOffset + (int) (Math.pow(-1, i)) * dy;

			float _degree = (float) (Math.toDegrees(Math.atan2(_xOffset,
					_yOffset)) - 90);

			float ratio = _yOffset / _xOffset;
			float realX = this.mCamera.getWidth() + arrow.getWidth() / 2.0f;
			float realY = ratio * realX + arrow.getY();

			float offRealX = realX - arrow.getX();
			float offRealY = realY - arrow.getY();

			float offset = (float) Math.sqrt(offRealX * offRealX + offRealY
					* offRealY);
			arrow.setRotationCenter(arrowFreeze.getRotationCenterX(),
					arrowFreeze.getRotationCenterY());
			arrow.setRotation(-_degree);

			float velocity = VELOCITY_ARROW;
			float realMoveDuration = offset / velocity;

			MoveModifier mod = new MoveModifier(realMoveDuration, arrow.getX(),
					realX, arrow.getY(), realY);
			arrow.registerEntityModifier(mod.deepCopy());

			if (mGeneral.getManaPoints() >= useManaArrowSkill) {

				if (id == 0) {
					arrow.attachChild(hoaTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.6f, 0,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 2) {
					arrow.attachChild(hanBangTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.6f, 2,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 4) {
					arrow.attachChild(mocTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.6f, 4,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 6) {
					arrow.setDamage(mGeneral.getAttackBasic() * 0.6f, 6,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 8) {
					arrow.setDamage(mGeneral.getAttackBasic() * 0.6f, 8,
							mSkillButton[buttonArrow].getLevel());
				}

				mGeneral.useMana(useManaArrowSkill);
			} else
				arrow.setDamage(mGeneral.getAttackBasic() * 0.6f);

			this.mArrowsList.add(arrow);
		}

		arrowFreeze.setRotation(-degree);
		arrowFreeze.setVisible(false);
		try {
			sArrowShoot.play();
		} catch (Exception e) {
		}
	}

	private void shoot3Arrows(final int id) {
		if (!mArrowCoolDown.checkValidity())
			return;

		float xOffset = this.xTouch - arrowFreeze.getX()
				- this.arrowFreeze.getWidth() / 2;
		float yOffset = this.yTouch - arrowFreeze.getY();
		float degree = (float) (Math.toDegrees(Math.atan2(xOffset, yOffset)) - 90);
		arrowFreeze.setRotation(-degree);
		arrowFreeze.setVisible(false);

		float dx = -TAN_3 * yOffset;
		float dy = TAN_3 * xOffset;

		for (int i = -1; i < 2; i++) {
			Arrow arrow = mArrows.obtainPoolItem();
			arrow.setPosition(arrowFreeze.getX(), arrowFreeze.getY());

			this.mMainScene.attachChildZIndex(1, arrow);

			float _xOffset = xOffset + (int) (Math.pow(-1, i)) * dx * i;
			float _yOffset = yOffset + (int) (Math.pow(-1, i)) * dy * i;

			float _degree = (float) (Math.toDegrees(Math.atan2(_xOffset,
					_yOffset)) - 90);

			float ratio = _yOffset / _xOffset;
			float realX = this.mCamera.getWidth() + arrow.getWidth() / 2.0f;
			float realY = ratio * realX + arrow.getY();

			float offRealX = realX - arrow.getX();
			float offRealY = realY - arrow.getY();

			float offset = (float) Math.sqrt(offRealX * offRealX + offRealY
					* offRealY);
			arrow.setRotationCenter(arrowFreeze.getRotationCenterX(),
					arrowFreeze.getRotationCenterY());
			arrow.setRotation(-_degree);

			float velocity = VELOCITY_ARROW;
			float realMoveDuration = offset / velocity;

			MoveModifier mod = new MoveModifier(realMoveDuration, arrow.getX(),
					realX, arrow.getY(), realY);
			arrow.registerEntityModifier(mod.deepCopy());

			if (mGeneral.getManaPoints() >= useManaArrowSkill) {
				if (id == 0) {
					arrow.attachChild(hoaTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.5f, 0,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 2) {
					arrow.attachChild(hanBangTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.5f, 2,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 4) {
					arrow.attachChild(mocTien());
					arrow.setDamage(mGeneral.getAttackBasic() * 0.5f, 4,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 6) {
					arrow.setDamage(mGeneral.getAttackBasic() * 0.5f, 6,
							mSkillButton[buttonArrow].getLevel());
				} else if (id == 8) {
					arrow.setDamage(mGeneral.getAttackBasic() * 0.5f, 8,
							mSkillButton[buttonArrow].getLevel());
				}

				mGeneral.useMana(useManaArrowSkill);

			} else
				arrow.setDamage(mGeneral.getAttackBasic() * 0.5f);

			this.mArrowsList.add(arrow);
		}

		arrowFreeze.setRotation(-degree);
		arrowFreeze.setVisible(false);
		try {
			sArrowShoot.play();
		} catch (Exception e) {
		}
	}

	// =================================================================================================//
	// CREATE ENEMy
	// =================================================================================================//

	private void addEnemy(final Enemy enemy) {
		if (enemy == null)
			return;
		runOnUpdateThread(new Runnable() {

			@Override
			public void run() {
				mEnemyList.add(enemy);
				mMainScene.attachChild(enemy);
			}
		});
	}

	private void createMelee(float xPos, float yPos) {
		Melee enemy = new Melee(5, 0, 0, mMeleeTRegion_Move.deepCopy());

		enemy.setPosition(xPos, yPos);
		enemy.animate(TIMEPEREACHFRAME_MELEE_MOVE);
		enemy.setHP(HP_MELEE);
		// enemy.setArmour(mArmourMelee);
		enemy.setAttackBasic(this.ATTACK_MELEE);
		enemy.setmFrameDurationEach_Attack(TIMEPEREACHFRAME_MELEE_SPAB);
		enemy.setmFrameDurationEach_Die(TIMEPEREACHFRAME_ENEMY_DIE);

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		MainGame.this.addEnemy(enemy);
		try {
			enemy.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			enemy.setZIndex(2);
		}

		enemy.handler.setVelocityX(-VELOCITY_X_MELEE);

		this.mMainScene.sortChildren();
	}

	private void createRange(float xPos, float yPos) {
		Range enemy = new Range(7, xPos, yPos, mRangeTRegion_Move.deepCopy());
		enemy.name = Constants.RANGE;
		enemy.setStatus(Constants.MOVE);
		enemy.animate(TIMEPEREACHFRAME_RANGE_MOVE);
		enemy.setHP(HP_RANGE);
		// enemy.setArmour(mArmourRange);
		enemy.setAttackBasic(ATTACK_RANGE);
		enemy.setmFrameDurationEach_Attack(TIMEPEREACHFRAME_RANGE_FIRE);
		enemy.setmFrameDurationEach_Die(TIMEPEREACHFRAME_ENEMY_DIE);

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		MainGame.this.addEnemy(enemy);
		try {
			enemy.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			enemy.setZIndex(2);
		}

		enemy.handler.setVelocityX(-VELOCITY_X_RANGE);

		this.mMainScene.sortChildren();
	}

	private void createSpell(float xPos, float yPos) {
		Spell enemy = new Spell(7, 0, 0, mSpellTiledTextureRegion.deepCopy());

		enemy.setPosition(xPos, yPos);
		enemy.setHP(HP_SPELL);
		// enemy.setArmour(mArmourSpell);
		enemy.setAttackBasic(ATTACK_RANGE);

		enemy.move();

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		MainGame.this.addEnemy(enemy);
		try {
			enemy.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			enemy.setZIndex(2);
		}

		enemy.handler.setVelocityX(-VELOCITY_X_RANGE);

		this.mMainScene.sortChildren();
	}

	private void createAurra(float xPos, float yPos) {
		Aurra enemy = new Aurra(3, 0, 0,
				mAurraMoveTiledTextureRegion.deepCopy());

		enemy.setPosition(xPos, yPos);
		enemy.setHP(HP_AURRA);
		// enemy.setArmour(mArmourAurra);
		enemy.setAttackBasic(ATTACK_AURRA);
		enemy.setDieTextureRegion(mAurraDieTiledTextureRegion);

		enemy.setDurationDie(150);
		enemy.setDurationMove(100);

		enemy.move();

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		MainGame.this.addEnemy(enemy);
		try {
			enemy.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			enemy.setZIndex(2);
		}

		enemy.handler.setVelocityX(-VELOCITY_X_AURRA);

		this.mMainScene.sortChildren();
	}

	private void createTank(float xPos, float yPos) {
		Tank enemy = new Tank(5, 0, 0, mTankMoveTextureRegion.deepCopy());

		enemy.setPosition(xPos, yPos);
		enemy.animate(TIMEPEREACHFRAME_TANK_MOVE);
		enemy.setHP(HP_TANK);
		// enemy.setArmour(mArmourTank);
		enemy.setAttackBasic(this.ATTACK_TANK);
		enemy.setmFrameDurationEach_Attack(TIMEPEREACHFRAME_TANK_SPAB);
		enemy.setmFrameDurationEach_Die(TIMEPEREACHFRAME_ENEMY_DIE);

		if (mEnemyList == null)
			mEnemyList = new ArrayList<Enemy>();

		MainGame.this.addEnemy(enemy);
		try {
			enemy.setZIndex(mEnemyList.get(mEnemyList.size()).getZIndex() + 1);
		} catch (Exception e) {
			enemy.setZIndex(2);
		}

		enemy.handler.setVelocityX(-VELOCITY_X_TANK);

		this.mMainScene.sortChildren();
	}

	public void rowThree(byte name) {
		Random rand = new Random();
		int yP = rand.nextInt(6) + 1;

		if (name == Constants.MELEE) {
			float xPos = mCamera.getWidth() + mMeleeTRegion_Move.getTileWidth()
					/ 2;
			for (int i = 0; i < 3; i++) {
				createMelee(xPos, yPosEnemyStart[yP + i - 1]);
			}
		} else if (name == Constants.RANGE) {
			float xPos = mCamera.getWidth() + mRangeTRegion_Move.getTileWidth()
					/ 2;
			for (int i = 0; i < 3; i++) {
				createRange(xPos, yPosEnemyStart[yP + i - 1]);
			}
		}
	}

	// //////////////////// IUpdateHandler ///////////////////////////////

	IUpdateHandler updateArrayList = new IUpdateHandler() {

		public void onUpdate(float arg0) {
			if (isTouch) {
				if (!isSkill) {
					float xOffset = MainGame.this.xTouch - arrowFreeze.getX()
							- MainGame.this.arrowFreeze.getWidth() / 2;
					float yOffset = MainGame.this.yTouch - arrowFreeze.getY();

					float degree = (float) (Math.toDegrees(Math.atan2(xOffset,
							yOffset)) - 90);

					crossBow.setRotation(-degree);
					arrowFreeze.setRotation(-degree);
				}
			}

			synchronized (mMagicsList) {
				Sprite magic;
				int i = 0;
				while (i < mMagicsList.size() && !isPause) {
					if (!mEngine.isRunning())
						break;
					magic = mMagicsList.get(i);
					if (magic.getX() <= 100) {
						sCityWallBroken.play();
						mGeneral.reduceBlood(ATTACK_SPELL);
						mMagics.recyclePoolItem(magic);
						mMagicsList.remove(i);
					} else
						i++;
				}
			}

			if (mSoundCircleList.size() > 0) {
				if (mEngine.isRunning())
					synchronized (mSoundCircleList) {
						SoundCircle circle;
						int i = 0;
						if (isAurra)
							isUpEnemy = true;
						while (i < mSoundCircleList.size() && !isPause) {
							if (!mEngine.isRunning())
								break;
							circle = mSoundCircleList.get(i);
							if (circle.timeLife() >= 3000) {
								mCircles.recyclePoolItem(circle);
								mSoundCircleList.remove(i);
							} else
								i++;
						}
					}
			} else {
				isUpEnemy = false;
			}

			if (mDoThuMagicList != null && mEngine.isRunning()) {
				DoThuMagic magic;

				int i = 0;
				while (i < mDoThuMagicList.size() && !isPause) {
					if (!mEngine.isRunning())
						break;
					magic = mDoThuMagicList.get(i);
					if (magic.isAttack()) {
						mGeneral.reduceBlood(Constants.DO_THU_INTEL
								* baseCoefficience);
						magic.stopInfluence();
						sCityWallBroken.play();

						mDoThuMagicPool.recyclePoolItem(magic);
						mDoThuMagicList.remove(i);
					} else
						i++;
				}
			}
			if (mArrowOfRangeList.size() > 0 && mEngine.isRunning()) {
				synchronized (mArrowOfRangeList) {
					EnemyArrow arrowOfRange;
					int i = 0;
					while (i < mArrowOfRangeList.size() && !isPause) {
						if (!mEngine.isRunning())
							break;
						arrowOfRange = mArrowOfRangeList.get(i);
						if (arrowOfRange.getX() < 140) {
							sArrowGoalCityWall.play();
							mGeneral.reduceBlood(ATTACK_RANGE);
							mArrowOfRange.recyclePoolItem(arrowOfRange);
							mArrowOfRangeList.remove(i);
						} else
							i++;
					}
				}
			}

			if (isFire) {
				shoot(useArrowSkill);
			} else
				arrowFreeze.setVisible(true);

			if (mEngine.isRunning()) {
				Arrow arrow;
				int k = 0;
				while (k < mArrowsList.size() && !isPause) {
					arrow = mArrowsList.get(k);

					if ((arrow.getX() > mCamera.getWidth())
							|| (arrow.getY() > mCamera.getHeight()
									+ arrow.getHeight())
							|| (arrow.getY() < -arrow.getHeight())) {
						mArrows.recyclePoolItem(arrow);
						mArrowsList.remove(arrow);
						break;
					}
					k++;

				}
			}

		}

		public void reset() {
		}

	};

	private long countF = 0;

	IUpdateHandler updateHuman = new IUpdateHandler() {

		public void onUpdate(float arg0) {
			// if (isNeedSort)
			sortListEnemy();

			updateStatusEnemy();

			updateBlood();
			updateMana();

			if (mGeneral.getHP() < 0)
				mGeneral.setHP(0);
			if (mGeneral.getManaPoints() < 0)
				mGeneral.setHP(0);

			mBloodText.setText(String.valueOf((int) mGeneral.getHP()));
			mManaText.setText(String.valueOf((int) mGeneral.getManaPoints()));

			if (mGeneral.getHP() < GENERAL_HP / 2 && !isFissured) {
				isFissured = true;
				citywall.setVisible(true);
				citywall.setTextureRegion(citywall_emergencyTextureRegion);
			} else if (mGeneral.getHP() >= GENERAL_HP / 2 + 50) {
				citywall.setVisible(false);
				isFissured = false;
			}

			if (mGeneral.getHP() < 0 && isFissured) {
				citywall.setTextureRegion(citywall_fireTextureRegion);
			}

			if (mGameStates == GameStates.GAME_PLAY) {
				long t = System.currentTimeMillis();
				if (t - countF > 20 && face_enemyGeneral.getX() > 0) {
					float distance = t - totalPauseGame - timeStartGame;
					face_enemyGeneral.setPosition(
							215 - (distance * 255 / totalTimeCallEnemy),
							face_enemyGeneral.getY());
					countF = t;
				}
				blood.setScaleX(32.0f * mGeneral.getHP() / GENERAL_HP);
				mana.setScaleX(32.0f * mGeneral.getManaPoints() / GENERAL_MANA);
			}
		}

		public void reset() {

		}

	};

	IUpdateHandler attack = new IUpdateHandler() {

		public void onUpdate(float arg0) {
			if (mArrowsList.size() > 0 && mEngine.isRunning()) {
				synchronized (mEnemyList) {
					Enemy enemy;
					for (int i = 0; i < mEnemyList.size() && !isPause; i++) {
						enemy = mEnemyList.get(i);
						if (enemy.getHP() <= 0)
							continue;
						int j = 0;
						while (j < mArrowsList.size() && !isPause) {
							Arrow arrow = mArrowsList.get(j);
							float x = arrow.getHeadX();
							float y = arrow.getHeadY();
							if (enemy.getYSort() < y || enemy.getY() > y) {
								j++;
								continue;
							}
							if ((enemy.isShot(x, y))) {
								boolean isStun = arrow.isStun();
								long timeStun = arrow.getStun();
								try {
									sArrowGoal.play();
								} catch (Exception e) {
								}
								enemy.reduceBlood(arrow.getDamage());
								mArrows.recyclePoolItem(arrow);
								mArrowsList.remove(j);
								if (enemy.getHP() <= 0) {
									enemy.allowChangeStatus(true);
									if (enemy.name == Constants.MELEE
											|| enemy.name == Constants.RANGE) {
										if (enemy.name == Constants.MELEE) {
											countGoldGamePlay = (countGoldGamePlay + EXP_MELEE * 2);
											mCoinText.setText(""
													+ (int) countGoldGamePlay);

										} else {
											countGoldGamePlay = (countGoldGamePlay + EXP_RANGE * 2);
											mCoinText.setText(""
													+ (int) countGoldGamePlay);

										}

										enemy.setmTextureRegion_next(mMeleeRangeDieTRegion
												.deepCopy());
										enemy.setStatus(Constants.DIE);
										enemy.handler.setEnabled(false);
									} else if (enemy.name == Constants.TANK) {

										countGoldGamePlay = (countGoldGamePlay + EXP_TANK * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);

										enemy.setmTextureRegion_next(mTankDieTextureRegion
												.deepCopy());
										enemy.setStatus(Constants.DIE);
										enemy.handler.setEnabled(false);
									} else if (enemy.name == Constants.NHAMNGAO) {

										((NhamNgao) enemy)
												.setState(NhamNgaoStates.DIE);
										((NhamNgao) enemy).isDie = true;
										((NhamNgao) enemy)
												.allowChangeStatus(true);

										float nhamNgaoExp = Constants.EXP_BOSS_NHAMNGAO;

										countGoldGamePlay = (countGoldGamePlay + nhamNgaoExp * 2);

										mCoinText.setText(""
												+ (int) countGoldGamePlay);

									} else if (enemy.name == Constants.DOTHU) {
										((DoThu) enemy)
												.setState(DoThuStates.RUNAWAY);
										((DoThu) enemy).isDie = true;
										enemy.allowChangeStatus(true);

										float doThuExp = Constants.EXP_BOSS_DOTHU;

										countGoldGamePlay = (countGoldGamePlay + doThuExp * 2);

										mCoinText.setText(""
												+ (int) countGoldGamePlay);
									} else if (enemy.name == Constants.FLAT_DRAGON) {
										((FlatDragon) enemy)
												.setState(FlatDragonStates.DIE);
										enemy.allowChangeStatus(true);

										float flatDragonExp = Constants.EXP_BOSS_FLAT_DRAGON;

										countGoldGamePlay = (countGoldGamePlay + flatDragonExp * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);
									} else if (enemy.name == Constants.SPELL) {

										countGoldGamePlay = (countGoldGamePlay + EXP_SPELL * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);

										enemy.setStatus(Constants.DIE);
										enemy.handler.setEnabled(false);
									} else if (enemy.name == Constants.AURRA) {

										countGoldGamePlay = (countGoldGamePlay + EXP_AURRA * 2);

										mCoinText.setText(""
												+ (int) countGoldGamePlay);

										enemy.setStatus(Constants.DIE);
										enemy.handler.setEnabled(false);
									}
									if (enemy.isBloodLine())
										enemy.mBloodLine.setVisible(false);
									continue;
								}
								if (!enemy.isBloodLine())
									enemy.setBloodLine(newBloodLine(enemy));
								enemy.mBloodLine.updateScale(enemy.getHP());

								if (!enemy.isFreezed() && isStun && enemy.getHP() > 0) {
									enemy.setTimeStun(timeStun);
									if (!enemy.isStun()) {
										enemy.setStun(true);
										enemy.allowChangeStatus(true);
									}
								}
							}
							j++;
						}
					}
				}
			}
			if (mISkillUse.size() > 0 && mEngine.isRunning()) {
				synchronized (mEnemyList) {
					AnimatedSkill skill;
					int i = 0;
					while (i < mISkillUse.size() && !isPause) {
						skill = mISkillUse.get(i);
						i++;

						long time = System.currentTimeMillis();

						if (skill.getName() == Constants.SKILL_BANG_HA) {
							if (skill.getStart() + 900 < time
									&& !skill.isDestroy()) {
								skill.setDestroy(true);
								try {
									sDestroyIce.play();
								} catch (Exception e) {
								}
							} else if (skill.getStart() + 1500 < time) {
								skill.stopInfluence();
								removeEntity(skill.returnSeft());
								mISkillUse.remove(skill);
								i--;
								continue;
							}
						} else if (skill.getName() == Constants.SKILL_LOI_QUANG_DIEN) {
							if (skill.getStart() + 1000 < time) {
								skill.stopInfluence();
								removeEntity(skill.returnSeft());
								mISkillUse.remove(skill);
								i--;
								continue;
							}
						} else if (skill.getName() == Constants.SKILL_TOA_DIA_CHAN) {
							if (skill.getStart() + 1250 < time) {
								skill.stopInfluence();
								removeEntity(skill.returnSeft());
								mISkillUse.remove(skill);
								i--;
								continue;
							}
						} else if (skill.getName() == Constants.SKILL_LIEU_NGUYEN_HOA) {
							if (skill.getStart() + 1350 < time) {
								skill.stopInfluence();
								removeEntity(skill.returnSeft());
								mISkillUse.remove(skill);
								i--;
								continue;
							}
						} else if (skill.getName() == Constants.SKILL_DAI_MOC_TRAN) {
							if (skill.getStart() + 700 < time) {
								skill.stopInfluence();
								removeEntity(skill.returnSeft());
								mISkillUse.remove(skill);
								i--;
								continue;
							}
						}

						if (!skill.isAttack())
							continue;

						int j = 0;
						Enemy enemy;
						while (j < mEnemyList.size() && !isPause) {
							enemy = mEnemyList.get(j);
							if (enemy.getHP() <= 0) {
								j++;
								continue;
							}
							final float pX = enemy.getBottomX();
							final float pY = enemy.getBottomY();

							if (skill.attack(pX, pY)) {

								if (skill.getName() == Constants.SKILL_TOA_DIA_CHAN) {
									if (enemy instanceof MinisterEnemy) {
										enemy.reduceBlood(enemy.getInitHP()
												* (0.04f * skill.getLevel() + 0.3f));
									} else
										enemy.reduceBlood(skill.getDamge());
								} else
									enemy.reduceBlood(skill.getDamge());

								if (enemy.getHP() <= 0) {
									enemy.allowChangeStatus(true);
									if (enemy.name == Constants.MELEE
											|| enemy.name == Constants.RANGE) {
										if (enemy.name == Constants.MELEE) {

											countGoldGamePlay = (int) (countGoldGamePlay + EXP_MELEE * 2);
											mCoinText.setText(""
													+ (int) countGoldGamePlay);

										} else {

											countGoldGamePlay = (int) (countGoldGamePlay + EXP_RANGE * 2);
											mCoinText.setText(""
													+ (int) countGoldGamePlay);

										}
										enemy.setmTextureRegion_next(mMeleeRangeDieTRegion
												.deepCopy());
										enemy.setStatus(Constants.DIE);
										enemy.unregisterUpdateHandler(enemy.handler);
									} else if (enemy.name == Constants.TANK) {

										countGoldGamePlay = (int) (countGoldGamePlay + EXP_TANK * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);

										enemy.setmTextureRegion_next(mTankDieTextureRegion
												.deepCopy());
										enemy.setStatus(Constants.DIE);
										enemy.unregisterUpdateHandler(enemy.handler);
									} else if (enemy.name == Constants.NHAMNGAO) {
										if (((NhamNgao) enemy).getState() != NhamNgaoStates.DIE) {
											((NhamNgao) enemy)
													.setState(NhamNgaoStates.DIE);
											((NhamNgao) enemy)
													.allowChangeStatus(true);
											((NhamNgao) enemy).isDie = true;

											float nhamNgaoExp = Constants.EXP_BOSS_NHAMNGAO
													* baseCoefficience;

											countGoldGamePlay = (countGoldGamePlay + nhamNgaoExp * 2);

											mCoinText.setText(""
													+ (int) countGoldGamePlay);

										}
									} else if (enemy.name == Constants.DOTHU
											&& ((DoThu) enemy).getState() != DoThuStates.RUNAWAY) {
										((DoThu) enemy)
												.setState(DoThuStates.RUNAWAY);
										((DoThu) enemy).allowChangeStatus(true);
										((DoThu) enemy).isDie = true;

										float doThuExp = Constants.EXP_BOSS_DOTHU
												* baseCoefficience;

										countGoldGamePlay = (countGoldGamePlay + doThuExp * 2);

										mCoinText.setText(""
												+ (int) countGoldGamePlay);

									} else if (enemy.name == Constants.FLAT_DRAGON) {
										((FlatDragon) enemy)
												.setState(FlatDragonStates.DIE);
										((FlatDragon) enemy)
												.allowChangeStatus(true);

										float flatDragonExp = Constants.EXP_BOSS_FLAT_DRAGON
												* baseCoefficience;

										countGoldGamePlay = (countGoldGamePlay + flatDragonExp * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);
									} else if (enemy.name == Constants.SPELL) {
										enemy.setStatus(Constants.DIE);
										enemy.unregisterUpdateHandler(enemy.handler);

										countGoldGamePlay = (int) (countGoldGamePlay + EXP_SPELL * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);
									} else if (enemy.name == Constants.AURRA) {
										enemy.setStatus(Constants.DIE);
										enemy.unregisterUpdateHandler(enemy.handler);

										countGoldGamePlay = (int) (countGoldGamePlay + EXP_AURRA * 2);
										mCoinText.setText(""
												+ (int) countGoldGamePlay);
									}
									if (enemy.isBloodLine())
										enemy.mBloodLine.setVisible(false);
								} else {
									if (skill.getName() == Constants.SKILL_BANG_HA) {
										if (!enemy.isFreezed()) {
											enemy.setFreezed(true);
											enemy.setTimeFreezed(skill
													.getCoolDownEnemy());
											enemy.allowChangeStatus(true);
											if (enemy.name == Constants.MELEE) {
												enemy.setmTextureRegion_next(mMeleeFreezed
														.deepCopy());
											} else if (enemy.name == Constants.RANGE) {
												enemy.setmTextureRegion_next(mRangeFreezed
														.deepCopy());
											} else if (enemy.name == Constants.TANK) {
												enemy.setmTextureRegion_next(mTankFreezed
														.deepCopy());
											} else if (enemy.name == Constants.SPELL) {
												enemy.setmTextureRegion_next(mSpellFreezed
														.deepCopy());
											} else if (enemy.name == Constants.AURRA) {
												enemy.setmTextureRegion_next(mAurraFreezed
														.deepCopy());
											}
										}
									}
									// else if (skill.getName() ==
									// Constants.SKILL_DAI_MOC_TRAN) {
									// enemy.setFreezed(true);
									// enemy.setTimeFreezed(skill
									// .getCoolDownEnemy());
									// }
									if (!enemy.isBloodLine())
										enemy.setBloodLine(newBloodLine(enemy));
									enemy.mBloodLine.updateScale(enemy.getHP());
									if (enemy.name == Constants.FLAT_DRAGON) {
										((FlatDragon) enemy).stopAnimation();
										((FlatDragon) enemy)
												.moveBack(
														enemy.getX()
																+ calculateMoveBack(skill
																		.getDamge()),
														random(80f, 280));
										if (mFireDragon.isVisible()) {
											mFireDragon.stopAnimation();
											mFireDragon.resetFire();
										}

									} else if (enemy.name == Constants.NHAMNGAO) {
										((NhamNgao) enemy)
												.moveBack(
														((NhamNgao) enemy)
																.getX()
																+ calculateMoveBack(skill
																		.getDamge()),
														random(50f, 300f));
										// nhamNgao.allowChangeStatus(true);
									} else if (enemy.name == Constants.DOTHU) {
										((DoThu) enemy)
												.moveBack(
														((DoThu) enemy).getX()
																+ calculateMoveBack(skill
																		.getDamge()),
														random(50f, 300f));
										// mDoThu.allowChangeStatus(true);
									}

								}
							}
							j++;
						}
						skill.stopInfluence();
					}
				}
			}

		}

		public void reset() {

		}

	};

	private int calculateMoveBack(float pDamage) {
		int x = 300;

		x += ((int) pDamage / 100) * 50;

		return x;
	}

	private int random(final int pMin, final int pMax) {
		int value = pMin;

		value = pMin + Constants.rand.nextInt(pMax - pMin + 1);
		if (value > pMax || value < pMin)
			return value = pMin;
		return value;
	}

	private float random(final float pMin, final float pMax) {
		float value = pMax;

		value = pMin + Constants.rand.nextFloat() * (pMax - pMin);

		if (value > pMax || value < pMin)
			return value = pMax;

		return value;
	}

	private int turn = 0;
	private int totalTurn = 0;
	private long pauseCallEnemy = 0;
	private long resumeCallEnemy = 0;
	private long totalPauseGame = 0;
	private long totalTimeCallEnemy = 0;

	private void getTotalGameTime() {
		turn = 0;
		totalTurn = mCoolDown.size();
		int k = mCoolDown.size();
		long sum = 0;

		for (int i = 0; i < k; i++) {
			sum += mCoolDown.get(i) * 1000;
		}

		totalTimeCallEnemy = (long) (sum) + 1000;

		countGoldGamePlay = 0;
	}

	private IUpdateHandler callEnemy = new IUpdateHandler() {

		@Override
		public void onUpdate(float arg0) {
			if (turn < totalTurn) {
				if (turn == 0) {
					timeStartGame = System.currentTimeMillis();
					countF = timeStartGame;
				}

				callEnemyTool();
			} else {
				for (int i = 0; i < 3; i++) {
					if (callMinisterEnemy[i] != -1) {
						createMinisterEnemy(i);
					}
				}
			}
		}

		@Override
		public void reset() {

		}

	};

	private void callEnemyTool() {
		if (!CoolDownCallEnemy.sharedCoolDown().checkValidity(
				mCoolDown.get(turn) * 1000))
			return;

		turn++;
		call(turn - 1);
	}

	private void call(int turn) {
		float factor = baseCoefficience * baseCoefficience;

		callMelee((int) Math.ceil(mCountMelee.get(turn) * factor));
		callRange((int) Math.ceil(mCountRange.get(turn) * factor));
		callTank((int) Math.ceil(mCountTank.get(turn) * factor));
		callSpell((int) Math.ceil(mCountSpell.get(turn) * factor));
		callAurra((int) Math.ceil(mCountAurra.get(turn) * factor));
	}

	private void callMelee(int quantity) {
		if (quantity == 0)
			return;
		// int coeff = stage / 15 + 1;
		// quantity = (int) (quantity * Math.pow(1.5, coeff));
		// if (quantity > 15)
		// quantity = 15;
		int plus = Constants.PLUS[MathUtils.random(0, 4)];
		switch (plus) {
		case Constants.PLUS_BIAS_LEFT:
			biasLeftMelee(quantity);
			break;
		case Constants.PLUS_BIAS_RIGHT:
			biasRightMelee(quantity);
			break;
		case Constants.PLUS_LINE:
			lineMelee(quantity);
			break;
		case Constants.PLUS_SOLDIERS:
			soldierMelee(quantity);
			break;
		case Constants.PLUS_CENTER:
			centerMelee(quantity);
			break;

		default:
			break;
		}
	}

	private void callRange(int quantity) {
		if (quantity == 0)
			return;
		int plus = Constants.PLUS[MathUtils.random(0, 4)];
		switch (plus) {
		case Constants.PLUS_BIAS_LEFT:
			biasLeftRange(quantity);
			break;
		case Constants.PLUS_BIAS_RIGHT:
			biasRightRange(quantity);
			break;
		case Constants.PLUS_LINE:
			lineRange(quantity);
			break;
		case Constants.PLUS_SOLDIERS:
			soldierRange(quantity);
			break;
		case Constants.PLUS_CENTER:
			centerRange(quantity);
			break;

		default:
			break;

		}
	}

	private void callTank(int quantity) {
		if (quantity == 0)
			return;
		int plus = Constants.PLUS[MathUtils.random(0, 4)];
		switch (plus) {
		case Constants.PLUS_BIAS_LEFT:
			biasLeftTank(quantity);
			break;
		case Constants.PLUS_BIAS_RIGHT:
			biasRightTank(quantity);
			break;
		case Constants.PLUS_LINE:
			lineTank(quantity);
			break;
		case Constants.PLUS_SOLDIERS:
			soldierTank(quantity);
			break;
		case Constants.PLUS_CENTER:
			centerTank(quantity);
			break;

		default:
			break;
		}
	}

	private void callSpell(int quantity) {
		if (quantity == 0)
			return;
		int plus = Constants.PLUS[MathUtils.random(0, 4)];
		switch (plus) {
		case Constants.PLUS_BIAS_LEFT:
			biasLeftSpell(quantity);
			break;
		case Constants.PLUS_BIAS_RIGHT:
			biasRightSpell(quantity);
			break;
		case Constants.PLUS_LINE:
			lineSpell(quantity);
			break;
		case Constants.PLUS_SOLDIERS:
			soldierSpell(quantity);
			break;
		case Constants.PLUS_CENTER:
			centerSpell(quantity);
			break;

		default:
			break;
		}
	}

	private static final float[] AURRA_YPOS = { 20, 250 };

	private void callAurra(int quantity) {
		if (quantity == 0)
			return;
		if (quantity == 1)
			createAurra(850, AURRA_YPOS[random(0, 1)]);
		else {
			for (int i = 0; i < quantity; i++) {
				createAurra(850, AURRA_YPOS[i] + MathUtils.random(-25, 25));
			}
		}

	}

	/*
	 * BiasRigh
	 */
	private void biasRightMelee(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createMelee(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[i]);
			count++;
		}
	}

	private void biasRightRange(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createRange(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[i]);
			count++;
		}
	}

	private void biasRightSpell(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createSpell(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[i]);
			count++;
		}
	}

	private void biasRightTank(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createTank(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[i]);
			count++;
		}

	}

	/*
	 * BiasLeft
	 */

	private void biasLeftMelee(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createMelee(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[4 - i]);
			count++;
		}

	}

	private void biasLeftTank(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createTank(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[4 - i]);
			count++;
		}

	}

	private void biasLeftRange(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createRange(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[4 - i]);
			count++;
		}

	}

	private void biasLeftSpell(int quantity) {
		int count = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			createSpell(800 + i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[4 - i]);
			count++;
		}

	}

	/*
	 * Line
	 */

	private void lineMelee(int quantity) {
		int count = 0;
		int rand = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			rand = (i % 2) * 10;

			createMelee(800 + k * Constants.X_BIAS, yPosEnemyStart[i] + rand);
			count++;
		}
	}

	private void lineTank(int quantity) {
		int count = 0;
		int rand = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			rand = (i % 2) * 10;

			createTank(800 + k * Constants.X_BIAS, yPosEnemyStart[i] + rand);
			count++;
		}
	}

	private void lineRange(int quantity) {
		int count = 0;
		int rand = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			rand = (i % 2) * 10;

			createRange(800 + k * Constants.X_BIAS, yPosEnemyStart[i] + rand);
			count++;
		}
	}

	private void lineSpell(int quantity) {
		int count = 0;
		int rand = 0;
		int k;
		int i;

		while (count < quantity) {
			i = count % 5;
			k = count / 5;
			rand = (i % 2) * 10;

			createSpell(800 + k * Constants.X_BIAS, yPosEnemyStart[i] + rand);
			count++;
		}
	}

	/*
	 * Soldier
	 */
	private void soldierMelee(int quantity) {

		int count = 0;
		int p = random(0, 3);
		int k;
		int i;
		while (count < quantity) {
			k = count / 16;
			i = count % 4;

			createMelee(800 + 2 * i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[p]);

			count++;
			if (i == 3) {
				p++;
				if (p == 4)
					p = 0;
			}
		}
	}

	private void soldierTank(int quantity) {

		int count = 0;
		int p = random(0, 3);
		int k;
		int i;
		while (count < quantity) {
			k = count / 16;
			i = count % 4;
			createTank(800 + 2 * i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[p]);
			count++;
			if (i == 3) {
				p++;
				if (p == 4)
					p = 0;
			}
		}
	}

	private void soldierRange(int quantity) {

		int count = 0;
		int p = random(0, 3);
		int k;
		int i;
		while (count < quantity) {
			k = count / 16;
			i = count % 4;
			createRange(800 + 2 * i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[p]);
			count++;
			if (i == 3) {
				p++;
				if (p == 4)
					p = 0;
			}
		}
	}

	private void soldierSpell(int quantity) {
		int count = 0;
		int p = random(0, 3);
		int k;
		int i;
		while (count < quantity) {
			k = count / 16;
			i = count % 4;
			createSpell(800 + 2 * i * Constants.X_BIAS + k * Constants.X_BIAS,
					yPosEnemyStart[p]);
			count++;
			if (i == 3) {
				p++;
				if (p == 4)
					p = 0;
			}
		}
	}

	/*
	 * Center
	 */

	private void centerMelee(int quantity) {
		int count = 0;
		int k = 1;
		int i = 0;

		while (count < quantity) {
			float yPos = yPosEnemyStart[2] + k * Constants.Y_BIAS / 2;

			createMelee(800 + k * Constants.X_BIAS, yPos - i * Constants.Y_BIAS);

			count++;
			if (i == k - 1) {
				i = 0;
				if (k < 5)
					k++;
			} else
				i++;
		}

	}

	private void centerTank(int quantity) {
		int count = 0;
		int k = 1;
		int i = 0;

		while (count < quantity) {
			float yPos = yPosEnemyStart[2] + k * Constants.Y_BIAS / 2;

			createTank(800 + k * Constants.X_BIAS, yPos - i * Constants.Y_BIAS);

			count++;
			if (i == k - 1) {
				i = 0;
				if (k < 5)
					k++;
			} else
				i++;
		}

	}

	private void centerRange(int quantity) {
		int count = 0;
		int k = 1;
		int i = 0;

		while (count < quantity) {
			float yPos = yPosEnemyStart[2] + k * Constants.Y_BIAS / 2;

			createRange(800 + k * Constants.X_BIAS, yPos - i * Constants.Y_BIAS);

			count++;
			if (i == k - 1) {
				i = 0;
				if (k < 5)
					k++;
			} else
				i++;
		}
	}

	private void centerSpell(int quantity) {
		int count = 0;
		int k = 1;
		int i = 0;

		while (count < quantity) {
			float yPos = yPosEnemyStart[2] + k * Constants.Y_BIAS / 2;

			createSpell(800 + k * Constants.X_BIAS, yPos - i * Constants.Y_BIAS);

			count++;
			if (i == k - 1) {
				i = 0;
				if (k < 5)
					k++;
			} else
				i++;
		}

	}

	private void removeEntity(final BaseSprite pBaseSprite) {
		if (pBaseSprite == null) {
			return;
		}

		try {
			pBaseSprite.setVisible(false);
			pBaseSprite.detachChildren();
			mMainScene.detachChild(pBaseSprite);
			BufferObjectManager.getActiveInstance().unloadBufferObject(
					pBaseSprite.getVertexBuffer());
		} catch (Exception e) {
		}

	}

	private void showPopUpAccount() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isPopup = true;
				sButtonClicked.play();
				mBoardPopupAccount.setPosition(255, 150);

				mAccountScene.setChildScene(mPopUpScene, false, false, true);
				mBoardPopupAccount.setScaleCenter(
						mBoardPopupAccount.getWidth() / 2,
						mBoardPopupAccount.getHeight() / 2);
				mBoardPopupAccount
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0, 1.2f)));
			}
		});
	}

	private void unShowPopUpAccount() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {

				isPopup = false;
				mBoardPopupAccount.setScale(0.5f);
				mAccountScene.clearChildScene();

			}
		});
	}

	private boolean[] isLoadedDataAccount;

	private void resetAccount(int accountIndex) {
		mGameSrotes[accountIndex].reset();

		int general = mGameSrotes[accountIndex].getGeneralLastUsed();
		mAccountIcon[accountIndex].setTextureRegion(mGeneralIcon[general]);
		generalLevelAccount[accountIndex].setText("Level "
				+ String.valueOf(mGameSrotes[accountIndex].getGeneral(general)
						.getLevel()));
		generalName[accountIndex].setText(Constants.GENERAL_NAME[general]);
		stageAccount[accountIndex].setText("Hồi : "
				+ String.valueOf(mGameSrotes[accountIndex].getStage() + 1));
		Coin_Text[accountIndex].setText(" x "
				+ String.valueOf(mGameSrotes[accountIndex].getMoney()));
		timeAccount[accountIndex].setText("Time : "
				+ mGameSrotes[accountIndex].getTime());
	}

	// ==============================================//
	// WINSCENE
	// =============================================//

	private Sprite mSnailBonus;
	private CameraScene mEndOfStartScene;

	private void onLoadEndOfStart() {
		mEngine.getTextureManager().loadTexture(mEndOfFinishBitmapTextureAtlas);

		mEndOfStartScene = new CameraScene(mCamera);
		mEndOfStartScene.setOnSceneTouchListener(this);
		mEndOfStartScene.setBackgroundEnabled(false);

		Sprite endOfStart = new Sprite(0, 0, mEndOfFinishTexture);
		mEndOfStartScene.attachChild(endOfStart);
	}

	private void onShowEndOfStart() {
		final String endOfStartString = "Kết thúc của một bắt đầu!\r\n Hãy chào đón phiên bản mới trong thời gian sớm nhất\r\n với những bất ngờ thú vị! ";

		Text endOfStartText = new Text(100, 50, mFontVietTo, endOfStartString,
				HorizontalAlign.CENTER);
		endOfStartText.setColor(0, 0, 0.8f);
		mEndOfStartScene.attachChild(endOfStartText);

		mMainScene.setChildScene(mEndOfStartScene, false, true, true);

		mGameStates = GameStates.GAME_END_OF_START;
		isEndOfStart = true;

		gameHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				isEndOfStart = false;
			}
		}, 2000);
	}

	private void onUnshowEndOfStart() {
		mMainScene.clearChildScene();
		mEngine.getTextureManager().unloadTexture(
				mEndOfFinishBitmapTextureAtlas);
		detackMainGameScene();
		setEquipmentScene();
	}

	private void onLoadResultScene() {
		resultScene = new CameraScene(this.mCamera);
		resultScene.setOnSceneTouchListener(this);
		holder = new Text(250, 350, mFontVietTo,
				"Chạm vào màn hình để tiếp tục");
		holder.setVisible(false);
		holder.setColor(0, 0, 0);

		trans = new Rectangle(0, 0, 800, 480);
		trans.setColor(1.0f, 1.0f, 1.0f);
		trans.setAlpha(0.05f);
		trans.setVisible(false);

		// ********** //
		// WinScene
		// ********** //

		mSnailBonus = new Sprite(100, 215, mSnailCoinIcon);

		mWinText = new ChangeableText(130, 15, mFontVietTo, "Chiến thắng");
		mWinText.setColor(0, 0, 0);

		winGame = new Sprite(-20, 90, this.winGameRegion);
		tableWinGame = new Sprite(275, 50, this.mTableWinGame);
		mSnailWin = new Sprite(70, 275, mSnailTextureRegion);
		mStageWin = new ChangeableText(160, 65, mFontVietTo, "Hồi xxxx",
				HorizontalAlign.CENTER, "stage xxx".length());
		mStageWin.setColor(0, 0, 0);
		mTotalEXP = new ChangeableText(150, 165, mFontVietTo, "EXP ",
				HorizontalAlign.CENTER, 15);
		mTotalEXP.setColor(0, 0, 0);
		mTimeStage = new ChangeableText(150, 115, mFontVietTo,
				"Thời gian xxxxxxxxxxx", HorizontalAlign.CENTER,
				"Thời gian xxxxxxxxxxx".length());
		mTimeStage.setColor(0, 0, 0);
		mBonusStage = new ChangeableText(160, 215, mFontVietTo,
				"bonus xxxxxxxxxx", HorizontalAlign.CENTER,
				"bonus xxxxxxxxxx".length());
		mBonusStage.setColor(0, 0, 0);

		// *********** //
		// GameOverScene
		// *********** //

		gameOver = new Sprite(-20, 125, gameOverRegion);
		this.mGameOverText = new Text(130, 15, this.mFontVietTo, "Thua trận",
				HorizontalAlign.CENTER);
		mGameOverText.setColor(0, 0, 0);

		resultScene.attachChild(tableWinGame);
		resultScene.attachChild(this.winGame);
		tableWinGame.attachChild(mSnailWin);
		tableWinGame.attachChild(mStageWin);
		tableWinGame.attachChild(mTotalEXP);
		tableWinGame.attachChild(mTimeStage);
		tableWinGame.attachChild(mBonusStage);
		tableWinGame.attachChild(mSnailBonus);
		tableWinGame.attachChild(mWinText);

		tableWinGame.attachChild(mGameOverText);
		resultScene.attachChild(gameOver);
		gameOver.setVisible(false);
		mGameOverText.setVisible(false);
		resultScene.attachChild(holder);

		resultScene.attachChild(trans);
		resultScene.setBackgroundEnabled(false);
	}

	private float calculateEXP() {

		return countGoldGamePlay / 2f;
	}

	private void updateGameOver() {
		int generalOpened = gameStore.getmGeneralOpened();
		gameStore.buyGold((int) (countGoldGamePlay));

		float totalEXP = calculateEXP();

		for (int i = 0; i < generalOpened; i++) {
			if (i == generalUse) {
				if (generalOpened > 1)
					gameStore.getGeneral(i).setEXP(totalEXP * 0.6f);
				else
					gameStore.getGeneral(i).setEXP(totalEXP);

			} else {
				gameStore.getGeneral(i).setEXP(
						totalEXP * 0.4f / (generalOpened - 1));
			}

			if (upLevelGeneral(gameStore.getGeneral(i).getEXP(), gameStore
					.getGeneral(i).getLevel())) {
				gameStore.getGeneral(i).upLevel();
				gameStore.getGeneral(i).setPointUpBasic(4, true);
				gameStore.getGeneral(i).setPointUpSkill(1, true);

				gameStore.getGeneral(i).upPointBasic(4);
				gameStore.getGeneral(i).upPointSkill(1);
			}
		}

		setUnLockListItem(true);
		setUnLockListSkill(true);
	}

	private void updateWinGame() {
		int generalOpened = gameStore.getmGeneralOpened();
		gameStore.buyGold((int) (countGoldGamePlay));
		gameStore.setRetry(0);

		float totalEXP = calculateEXP();

		for (int i = 0; i < generalOpened; i++) {
			if (i == generalUse) {
				if (generalOpened > 1)
					gameStore.getGeneral(i).setEXP(totalEXP * 0.6f);
				else
					gameStore.getGeneral(i).setEXP(totalEXP);

			} else {
				gameStore.getGeneral(i).setEXP(
						totalEXP * 0.4f / (generalOpened - 1));
			}

			if (upLevelGeneral(gameStore.getGeneral(i).getEXP(), gameStore
					.getGeneral(i).getLevel())) {
				gameStore.getGeneral(i).upLevel();
				gameStore.getGeneral(i).setPointUpBasic(4, true);
				gameStore.getGeneral(i).setPointUpSkill(1, true);

				gameStore.getGeneral(i).upPointBasic(4);
				gameStore.getGeneral(i).upPointSkill(1);

			}
		}
		
		if (stage == Constants.STAGE_BOSS_1 || stage == Constants.STAGE_BOSS_2 || stage == Constants.STAGE_BOSS_3 
				|| stage == Constants.STAGE_BOSS_4 || stage == Constants.STAGE_BOSS_DOTHU_2 || stage == Constants.STAGE_BOSS_FLAT_DRAGON_2 
				|| stage == Constants.STAGE_BOSS_NHAMNGAO_2 ) {
			gameStore.buyTayTuyKinh(1);
		}
		stage++;

		if (gameStore.getmGeneralOpened() == 1 && stage == 20) {
			gameStore.newGeneral(this);
		} else if (gameStore.getmGeneralOpened() == 2 && stage == 40) {
			gameStore.newGeneral(this);
		}
		
		gameStore.setStage(stage);

		setUnLockListItem(true);
		setUnLockListSkill(true);
	}

	private boolean upLevelGeneral(float exp, int level) {
		if (exp > EXP_LEVEL[level])
			return true;

		return false;
	}

	private void clearMainScene() {
		if (mDoThuMagicList != null) {
			DoThuMagic magic;
			while (mDoThuMagicList.size() > 0) {
				magic = mDoThuMagicList.get(0);
				mDoThuMagicList.remove(0);
				mDoThuMagicPool.recyclePoolItem(magic);
			}

		}

		if (mArrowOfRangeList.size() > 0) {
			EnemyArrow arrow_r;
			while (mArrowOfRangeList.size() > 0) {
				arrow_r = mArrowOfRangeList.get(0);
				mArrowOfRangeList.remove(0);
				mArrowOfRange.recyclePoolItem(arrow_r);
			}
		}

		if (mMagicsList.size() > 0) {
			Sprite magic;
			while (mMagicsList.size() > 0) {
				magic = mMagicsList.get(0);
				mMagicsList.remove(0);
				mMagics.recyclePoolItem(magic);
			}
		}

		if (mArrowsList.size() > 0) {
			Arrow arrow;
			while (mArrowsList.size() > 0) {
				arrow = mArrowsList.get(0);
				mArrowsList.remove(0);
				mArrows.recyclePoolItem(arrow);
			}
		}
		if (mEnemyList.size() > 0) {
			Enemy enemy;
			while (mEnemyList.size() > 0) {
				enemy = mEnemyList.get(0);
				mEnemyList.remove(0);
				enemy.clearEntityModifiers();
				enemy.clearUpdateHandlers();
				enemy.detachChildren();
				removeEntity(enemy);
			}
		}

		if (mISkillUse.size() > 0) {
			ISkill skill;
			while (mISkillUse.size() > 0) {
				skill = mISkillUse.get(0);
				mISkillUse.remove(skill);
				removeEntity(skill.returnSeft());
			}
		}

	}

	private void win() {
		if (mGameStates == GameStates.GAME_WIN)
			return;

		try {
			sWinGame.play();
			if (mDrum.isPlaying()) {
				mDrum.pause();
			}

			if (mSpellFlying.isPlaying()) {

				mSpellFlying.pause();
			}

			if (mEnemyMove.isPlaying()) {
				mEnemyMove.pause();
			}
		} catch (Exception e) {
		}

		mGameStates = GameStates.GAME_WIN;
		gameOver.setVisible(false);
		winGame.setVisible(true);
		mWinText.setVisible(true);
		mGameOverText.setVisible(false);
		mTotalEXP.setText("EXP  " + (int) calculateEXP());
		mTimeStage.setText("Thời gian  " + String.valueOf(countTimeGame / 1000)
				+ "s");
		mBonusStage.setText(" x " + (int) countGoldGamePlay);

		mStageWin.setText("Hồi " + String.valueOf(stage + 1));
		this.mMainScene.setChildScene(resultScene, false, true, true);

		try {
			mBackgroundMusic.pause();
		} catch (Exception e) {
		}
		trans.setVisible(true);

		lastGameStage = stage;

		holdScreen();

		updateWinGame();

		onVisibleHUD();

		onUnLoadResourcesBoss(lastGameStage);

		isPause = true;
	}

	private void onUnLoadResourcesBoss(final int stage) {
		switch (stage) {
		case Constants.STAGE_BOSS_NHAMNGAO_1:
			mEngine.getTextureManager().unloadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().unloadTexture(
					mNhamNgaoBitmapAttackAtlas);
			break;

		case Constants.STAGE_BOSS_NHAMNGAO_2:
			mEngine.getTextureManager().unloadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().unloadTexture(
					mNhamNgaoBitmapAttackAtlas);
			break;

		case Constants.STAGE_BOSS_DOTHU_1:
			mEngine.getTextureManager().unloadTexture(mDoThuBitmapTextureAtlas);
			break;

		case Constants.STAGE_BOSS_DOTHU_2:
			mEngine.getTextureManager().unloadTexture(mDoThuBitmapTextureAtlas);
			break;

		case Constants.STAGE_BOSS_FLAT_DRAGON_1:
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().unloadTexture(mSkillFireDragonBitmap);
			break;

		case Constants.STAGE_BOSS_FLAT_DRAGON_2:
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().unloadTexture(mSkillFireDragonBitmap);
			break;

		case Constants.STAGE_BOSS_1:
			mEngine.getTextureManager().unloadTexture(mDoThuBitmapTextureAtlas);

			mEngine.getTextureManager().unloadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().unloadTexture(
					mNhamNgaoBitmapAttackAtlas);
			break;

		case Constants.STAGE_BOSS_2:
			mEngine.getTextureManager().unloadTexture(mDoThuBitmapTextureAtlas);

			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().unloadTexture(mSkillFireDragonBitmap);
			break;

		case Constants.STAGE_BOSS_3:
			mEngine.getTextureManager().unloadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().unloadTexture(
					mNhamNgaoBitmapAttackAtlas);

			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().unloadTexture(mSkillFireDragonBitmap);
			break;

		case Constants.STAGE_BOSS_4:
			mEngine.getTextureManager().unloadTexture(mDoThuBitmapTextureAtlas);

			mEngine.getTextureManager().unloadTexture(mNhamNgaoBitmapAtlas);
			mEngine.getTextureManager().unloadTexture(
					mNhamNgaoBitmapAttackAtlas);

			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapAttack);
			mEngine.getTextureManager().unloadTexture(mFlatDragonBitmapMove);
			mEngine.getTextureManager().unloadTexture(mSkillFireDragonBitmap);
			break;

		default:
			break;
		}
	}

	// ==============================================//
	// PAUSESCENE
	// =============================================//

	// ==============================================//
	// GAME OVER
	// =============================================//

	private void gameOver() {
		if (mGameStates == GameStates.GAME_OVER)
			return;

		mGameStates = GameStates.GAME_OVER;

		this.mMainScene.setChildScene(this.resultScene, false, true, true);
		try {
			mBackgroundMusic.pause();
			sGameOver.play();
			if (mDrum.isPlaying()) {
				mDrum.pause();
			}
			if (mSpellFlying.isPlaying()) {

				mSpellFlying.pause();
			}
			if (mEnemyMove.isPlaying()) {
				mEnemyMove.pause();
			}
		} catch (Exception e) {
		}

		this.winGame.setVisible(false);
		gameOver.setVisible(true);

		mGameOverText.setVisible(true);
		mWinText.setVisible(false);

		trans.setVisible(true);

		mTimeStage.setText("Thời gian  " + String.valueOf(countTimeGame / 1000)
				+ "s");
		mStageWin.setText("Hồi : " + String.valueOf(stage + 1));
		mTotalEXP.setText("EXP : " + (int) (countGoldGamePlay / 2));
		mBonusStage.setText(" x " + (int) (countGoldGamePlay));

		holdScreen();

		updateGameOver();

		onVisibleHUD();

		isPause = true;

	}

	private void onVisibleHUD() {
		magic_circle.setVisible(false);
		mSkillButton[0].setVisible(false);
		mSkillButton[1].setVisible(false);
		mSkillButton[2].setVisible(false);
		contain_blood.setVisible(false);
		contain_mana.setVisible(false);
		contain_enemy.setVisible(false);
		mana.setVisible(false);
		blood.setVisible(false);
		face_general.setVisible(false);
		pause_button.setVisible(false);
		face_enemyGeneral.setVisible(false);
		mManaText.setVisible(false);
		mBloodText.setVisible(false);

	}

	private Text holder;

	private boolean isHold = false;
	private boolean isEndOfStart = false;

	private void holdScreen() {

		final LoopEntityModifier loop = new LoopEntityModifier(
				new ParallelEntityModifier(new ScaleAtModifier(2, 0.95f, 1,
						holder.getWidth() / 2, holder.getHeight() / 2),
						new AlphaModifier(2, 0.1f, 1)));

		isHold = true;

		gameHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				holder.setVisible(true);
				holder.registerEntityModifier(loop);
				isHold = false;
				countTimeGame = 0;
			}
		}, 2000);

		gameStore.setTime(countTimeGame);
//		QplayAchievementUserInfo.getInstance(this, this).onStopGame();
	}

	// ==========================================================================================//
	// TOUCH
	// ==========================================================================================//

	public boolean onMenuItemClicked(MenuScene arg0, IMenuItem menuItem,
			float arg2, float arg3) {
		switch (mGameStates) {
		case GAME_MENU:
			switch (menuItem.getID()) {
			case Constants.PLAY_MENU:
				// tracker.trackPageView("/coloa/level/" + )
				if (tracker != null)
					tracker.trackPageView("/coloa/play");
				try {
					sTransitionScene.play();
				} catch (Exception e) {
				}
				setAccountScene();
				break;
			case Constants.INFO:
				isShowDialogue = true;
				if (tracker != null)
					tracker.trackPageView("/coloa/info");
				gameHandler.post(new Runnable() {

					@Override
					public void run() {
						showDialog(2);
					}
				});
				break;
			case Constants.SHARE:
				if (tracker != null)
					tracker.trackPageView("/coloa/share");
				loadParam.openShareDialog(getString(R.string.title_share),
						getString(R.string.subject_mail),
						getString(R.string.share_content));
				break;
			case Constants.MORE:
				isShowDialogue = true;
				if (tracker != null)
					tracker.trackPageView("/coloa/download");
				loadParam.openDownloadLink();

				break;
			case Constants.EXIT:
				isShowDialogue = true;
				if (tracker != null)
					tracker.trackPageView("/coloa/exit");
				gameHandler.post(new Runnable() {

					@Override
					public void run() {
						showDialog(1);
					}
				});
				break;
			}
			break;

		case GAME_SHOP:
			sButtonClicked.play();
			switch (menuItem.getID()) {

			case CHECK_REMOVE_0:
				checkRemoveSkill[0].setCheck(!checkRemoveSkill[0].isCheck());
				isSelectRemove[0] = checkRemoveSkill[0].isCheck();
				break;
			case CHECK_REMOVE_1:
				checkRemoveSkill[1].setCheck(!checkRemoveSkill[1].isCheck());
				isSelectRemove[1] = checkRemoveSkill[1].isCheck();
				break;
			case CHECK_REMOVE_2:
				checkRemoveSkill[2].setCheck(!checkRemoveSkill[2].isCheck());
				isSelectRemove[2] = checkRemoveSkill[2].isCheck();
				break;

			default:
				break;
			}
			break;

		default:
			break;
		}

		return false;
	}

	// ====================================================================================================//
	// GAME STATUS
	// ====================================================================================================//

	@Override
	public void onClick(MyAnimatedButton pButtonSprite, float pTouchAreaLocalX,
			float pTouchAreaLocalY) {
		switch (pButtonSprite.getID()) {
		/** InforScene */
		case UP:
			if (skillClicked != null) {
				sButtonClicked.play();
				if (generalStore.getPointUpSkill() > 0) {
					upgradeSkill(skillClicked.getContainBy());
				} else {
					unShowInforSkill();
					showBuySnail();
					if (totalGold < Constants.PRICE_SKILL_POINT) {
						paySnail(true);
					} else {
						onToast("Bạn cần mua thêm điểm kĩ năng!");
					}
				}
			}
			break;
		case PLUS:
			if (isItemMenu) {
				if (isBuy) {
					sButtonClicked.play();

					if (!isNeedPaySnail) {
						runOnUiThread(new Runnable() {

							public void run() {
								if (itemClicked != null) {
									pay();
									unShowInfoItem();
								}
							}
						});
					} else {
						paySnail(true);
					}
				} else if (isUsedItem) {
					sButtonClicked.play();
					runOnUiThread(new Runnable() {

						public void run() {
							if (itemClicked != null) {
								useItem(itemClicked);
								unShowInfoItem();
							}
						}
					});
				}
			} else {
				if (isLearning) {
					sButtonClicked.play();
					runOnUpdateThread(new Runnable() {

						@Override
						public void run() {
							if (skillClicked != null) {
								if (learnSkill()) {
									useSkill(skillClicked);
									unShowInforSkill();
								} else {
									if (totalGold >= Constants.PRICE_REMOVE_SKILL) {
										unShowInforSkill();
										showBuySnail();
										onToast("Bạn cần mua thêm điểm kĩ năng!");
									} else {
										unShowInforSkill();
										showBuySnail();
										paySnail(true);
									}
								}
							}
							isLearning = false;

						}
					});
				} else if (isUsedSkill) {
					sButtonClicked.play();
					runOnUpdateThread(new Runnable() {

						@Override
						public void run() {
							if (skillClicked != null) {
								useSkill(skillClicked);
								unShowInforSkill();
							}
						}
					});
				}
			}
			break;
		case DESTROY:
			sButtonClicked.play();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (isItemMenu)
						unShowInfoItem();
					else
						unShowInforSkill();
				}
			});
			break;
		case SALE:
			if (itemClicked != null) {
				sButtonClicked.play();
				sale(itemClicked.getID());
				unShowInfoItem();
			} 
			break;

		case EXIT_BOARD_PRICE:
			sButtonClicked.play();
			unShowBuySnail();
			warningUpGeneral();
			break;

		case COMPLETE_REMOVE:
			if (gameStore.getcTayTuyKinh() > 0) {
				sButtonClicked.play();
				unShowRemoveSkill(true);
			} else {
				sButtonClicked.play();
				unShowRemoveSkill(false);
				showPopupRemoveSkill();
			}
			break;
		case DESTROY_REMOVE:
			sButtonClicked.play();
			for (int i = 0; i < 3; i++) {
				if (isSelectRemove[i]) {
					isSelectRemove[i] = false;
					checkRemoveSkill[i].updateTextureRegion(
							mRemovableTextureRegion, true);
				}
			}
			mEquipmentScene.clearChildScene();
			isRemoveSkill = false;
			isChildScene = false;
			break;

		case UP_STRENG:
			if (generalStore.getPointUpBasic() > 0) {
				upStreng();
			} else if (totalGold > Constants.PRICE_BASIC_POINT) {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				onToast("Bạn cần mua thêm điểm cơ bản");
			} else {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				paySnail(true);
			}
			break;
		case UP_AGILITY:
			if (generalStore.getPointUpBasic() > 0) {
				upAgility();
			} else if (totalGold > Constants.PRICE_BASIC_POINT) {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				onToast("Bạn cần mua thêm điểm cơ bản");
			} else {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				paySnail(true);
			}
			break;
		case UP_INTEL:
			if (generalStore.getPointUpBasic() > 0) {
				upIntel();
			} else if (totalGold > Constants.PRICE_BASIC_POINT) {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				onToast("Bạn cần mua thêm điểm cơ bản");
			} else {
				sButtonClicked.play();
				unShowUpgradeGeneral();
				showBuySnail();
				paySnail(true);
			}
			break;

		case UP_WARNING:
			sButtonClicked.play();
			showUpgradeGeneral();
			break;

		case UP_COMPLETE:
			sButtonClicked.play();
			unShowUpgradeGeneral();
			break;

		case CONTAIN_SNAIL:
			sButtonClicked.play();
			showBuySnail();
			break;

//		case EXIT_BOARD_FREE:
//			sButtonClicked.play();
//			mBoardInforFree.setVisible(false);
//			removeEntity(mBoardInforFree);
//			mButton.setVisible(false);
//			removeEntity(mButton);
//
//			mMenuScene.setChildScene(mStaticMenuScene, false, true, true);
//			gameHandler.post(new Runnable() {
//
//				@Override
//				public void run() {
//					useGeneral.setVisible(false);
//					adView.setVisibility(View.VISIBLE);
//				}
//			});
//
//			break;

		case BUY_SNAIL:
			sButtonClicked.play();
			paySnail(false);

			break;

		case BUY_BASIC_POINT:
			if (totalGold >= Constants.PRICE_BASIC_POINT) {
				buyBasicPoint();
			} else {
				sButtonClicked.play();
				paySnail(true);
			}
			break;

		case BUY_SKILL_POINT:
			if (totalGold >= Constants.PRICE_SKILL_POINT) {
				buySkillPoint();
			} else {
				sButtonClicked.play();
				paySnail(true);
			}
			break;

		case PLAY_GAME:
			try {
				sTransitionScene.play();
			} catch (Exception e) {
			}
			if (stage > 2 && gameStore.isNewBie()) {
				checkNewBie();
			} else {
				runOnUpdateThread(new Runnable() {

					public void run() {
						if (testEquipment() != -1) {
							newGame();
							setMainGameScene();
						} else {
							text.setVisible(true);

							Timer time = new Timer();
							time.schedule(new TimerTask() {

								@Override
								public void run() {
									text.setVisible(false);
									text.setColor(0, 0, 0);
								}
							}, 1000);

						}

					}
				});
			}
			break;
		case SELECT_SKILL:
			isItemMenu = false;
			runOnUiThread(new Runnable() {

				public void run() {
					onSelect();
				}
			});

			break;
		case SELECT_ITEM:
			isItemMenu = true;
			runOnUiThread(new Runnable() {

				public void run() {
					onSelect();
				}
			});
			break;

		case YES_POPUP:
			if (isPopup) {
				onToast("Vui lòng chờ . . .");
				mGameSrotes[resetAccount].onLoadStep2(this);
				resetAccount(resetAccount);
				unShowPopUpAccount();
			}
			break;

		case NO_POPUP:
			if (isPopup) {
				sButtonClicked.play();
				unShowPopUpAccount();
				resetAccount = -1;
			}
			break;

		case PAY_SNAIL_REMOVE_SKILL_POPUP:
			sButtonClicked.play();
			paySnail(false);
			break;

		case BUY_REMOVE_SKILL_POPUP:
			if (totalGold >= Constants.PRICE_REMOVE_SKILL) {
				buyRemoveSkill();
			} else {
				// unShowPopupRemoveSkill();
				paySnail(true);
			}
			break;

		case EXIT_REMOVE_SKILL_POPUP:
			unShowPopupRemoveSkill();
			break;

		case DETAIL_REMOVE_SKILL:
			sButtonClicked.play();
			unShowRemoveSkill(false);
			showPopupRemoveSkill();
			break;

		default:
			break;
		}

	}

	private static final String mNotifi = "Không đủ ốc. Bạn cần nạp thêm ốc!";

	private void paySnail(final boolean isToast) {
		gameHandler.post(new Runnable() {

			@Override
			public void run() {
				isShowDialogue = true;
				if (isToast) {
					Toast.makeText(MainGame.this, mNotifi, Toast.LENGTH_SHORT)
							.show();
				}
//				paymentUpdate.showDefaultPayment();
			}
		});
	}

	private void buySkillPoint() {
		if (gameStore.pay(Constants.PRICE_SKILL_POINT)) {
			sButtonClicked.play();
			generalStore.setPointUpSkill(1, true);
			reLoadPriceBoard(true, false, true);
		}
	}

	private void buyBasicPoint() {
		if (gameStore.pay(Constants.PRICE_BASIC_POINT)) {
			sButtonClicked.play();
			generalStore.setPointUpBasic(1, true);
			reLoadPriceBoard(true, true, false);
		}
	}

	private void reLoadPriceBoard(boolean isTotalGold, boolean isBasic,
			boolean isSkill) {
		totalGold = gameStore.getMoney();
		if (isTotalGold) {
			totalGold_display.setText("x " + String.valueOf(totalGold));
		}
		mTotalSnail.setText(" x " + String.valueOf(totalGold));
		if (isBasic)
			mBuyablePointBasic.setText(String.valueOf(generalStore
					.getPointUpBasic()));
		if (isSkill)
			mBuyablePointSkill.setText(String.valueOf(generalStore
					.getPointUpSkill()));
	}

	private void showBuySnail() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isChildScene = true;
				mEquipmentScene.setChildScene(mPriceSnailScene, false, false,
						true);
				mBoardPriceSnail.setScaleCenter(
						mBoardPriceSnail.getWidth() / 2,
						mBoardPriceSnail.getHeight() / 2);
				mBoardPriceSnail
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0.5f, 1)));

				reLoadPriceBoard(false, true, true);

				isBuySnail = true;
				select_item.setVisible(false);
				select_skill.setVisible(false);
				contain_gold.setVisible(false);
				play.setVisible(false);
			}
		});
	}

	private void unShowBuySnail() {
		isChildScene = false;
		mEquipmentScene.clearChildScene();
		mBoardPriceSnail.setScale(0.5f);
		isBuySnail = false;
		select_item.setVisible(true);
		select_skill.setVisible(true);
		contain_gold.setVisible(true);
		play.setVisible(true);
	}

	private void showUpgradeGeneral() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				isChildScene = false;
				mEquipmentScene.setChildScene(mUpgradeGeneralScene, false,
						false, true);
				mBoardUpgrade.setScaleCenter(mBoardUpgrade.getWidth() / 2,
						mBoardUpgrade.getHeight() / 2);
				mBoardUpgrade
						.registerEntityModifier(new ParallelEntityModifier(
								new AlphaModifier(0.25f, 0, 1),
								new ScaleModifier(0.25f, 0.5f, 1)));

				pointSkill.setText(String.valueOf(generalStore
						.getPointUpSkill()));
				pointBasic.setText(String.valueOf(generalStore
						.getPointUpBasic()));

				pointStreng.setText(String.valueOf(generalStore.getStreng()));
				pointAgility.setText(String.valueOf(generalStore.getAgility()));
				pointIntel
						.setText(String.valueOf(generalStore.getIntelligent()));

				select_item.setVisible(false);
				select_skill.setVisible(false);
				contain_gold.setVisible(false);
				play.setVisible(false);

				mWarningUpgrade.stopAnimation(0);

				isUpgradeScene = true;
			}
		});
	}

	private void upStreng() {
		if (generalStore.getPointUpBasic() < 1)
			return;

		sButtonClicked.play();
		generalStore.setPointUpBasic(1, false);
		generalStore.upgradeStreng(1);

		pointStreng.setText(String.valueOf(generalStore.getStreng()));
		pointBasic.setText(String.valueOf(generalStore.getPointUpBasic()));

		reLoadGeneralInfo(true);
	}

	private void upAgility() {
		if (generalStore.getPointUpBasic() < 1
				|| generalStore.getAgility() >= 200)
			return;

		sButtonClicked.play();
		generalStore.setPointUpBasic(1, false);
		generalStore.upgradeAgility(1);

		pointAgility.setText(String.valueOf(generalStore.getAgility()));
		pointBasic.setText(String.valueOf(generalStore.getPointUpBasic()));

		reLoadGeneralInfo(true);
	}

	private void upIntel() {
		if (generalStore.getPointUpBasic() < 1)
			return;

		sButtonClicked.play();
		generalStore.setPointUpBasic(1, false);
		generalStore.upgradeIntelligent(1);

		pointIntel.setText(String.valueOf(generalStore.getIntelligent()));
		pointBasic.setText(String.valueOf(generalStore.getPointUpBasic()));

		reLoadGeneralInfo(true);
	}

	private void unShowUpgradeGeneral() {
		isChildScene = false;
		mEquipmentScene.clearChildScene();
		mBoardUpgrade.setScale(0.5f);
		mBoardUpgrade.setInitialPosition();
		select_item.setVisible(true);
		select_skill.setVisible(true);
		contain_gold.setVisible(true);
		play.setVisible(true);
		isUpgradeScene = false;

		warningUpGeneral();
	}

	private void warningUpGeneral() {
		if (generalStore.getPointUpBasic() > 1)
			mWarningUpgrade.animate(400);
		else {
			mWarningUpgrade.stopAnimation(0);
		}

	}

	protected void onAssetsLoaded() {

		gameHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				setMenuScene();
				mMenuScene.setChildScene(mStaticMenuScene, false, true, true);
				
				runOnUpdateThread(new Runnable() {
					
					@Override
					public void run() {
						onLoadAccountScene();
						onLoadEquipmentScene();
						onLoadMainGameScene();
					}
				});
			}
		}, 1000);

	}

	protected void assetsToLoad() {

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// //////// Resource of Sound and Music
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////
		onLoadSoundMusic();

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// //////// Resource of MenuScene
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadResourcesMenu();
		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// //////// Resource of AccountScene
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadResourcesAccount();

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// ////////Resource of EquipmentScene
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadResourcesEquipment();

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// ////////Resource of MainGameScene
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadResourcesMainGame();

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// //////// DATA
		// /////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadTextFile();
		try {
			onLoadGameStoreAccount();
		} catch (InvalidChecksumException e) {
			e.printStackTrace();
		}

		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Load Scenes
		// //////////////////////////////////////////////////////////////////////////////////////////////////////////////

		onLoadMenuScene();

		mGameStates = GameStates.GAME_MENU;

		gameHandler.obtainMessage(1).sendToTarget();
		loadFinish = true;
	}

	// ============================================================================================================//
	// Nap tien
	// ============================================================================================================//

	public static final String IMPLEMENT_ANDROID_MARKET = "1";
	public static final String IMPLEMENT_QPLAY_VN = "2";
	public static final String IMPLEMENT_VIMARKET = "3";
	public static final String IMPLEMENT_OTHER = "4";
	public static boolean HAS_SMS = false;
	public static final boolean HAS_PAYMENT = true;
	public static boolean NO_UPDATE = false;

	public static final String SMS_EXTRA_CODE = "sunnet_coloathanh";

	public static final int DEFAULT_VERSION_CODE = 20;

	public static String DEFAULT_ITEM_PRODUCT_ID = "1";
	public static String DEFAULT_PRODUCT_ID = "1";
	public static String DEFAULT_CHANNEL_ID = "1";
	public static final String DEFAULT_VERSION = "1.0";
	public static final String DEFAULT_ITEM_ID = "SMSUP150";

	public static final int DEFAULT_TIMES = 10;
	public static final int DEFAULT_COINS = 3000;
//	private static final int DEFAULT_ADD_COINS = 150000;
	public static final int DEFAULT_COINS_PLAYING = 300;
	public static final int DEFAULT_COINS_ITEM_POSTSCORE = 1500;

	public static final String DEFAULT_PREFIX_NUMBER = "6711";
	public static String DEFAULT_MESSAGE_CODE = "ADR";

//	private PaymentManagerTakeItAll paymentUpdate;

	public static ConfigNode mConfigNode;

	public ConfigClient mConfigClient;

	// version number
	public static int sVersionNumber = DEFAULT_VERSION_CODE;
	public static String sVersionName = "";
	public static boolean sblnDenyUpdate = false;

	public SunnetLoadParam loadParam;

	public static final String UA_GOOGLE_ANALYTIC = "UA-25055531-49";
	private GoogleAnalyticsTracker tracker;
//	private int mAddCoins = DEFAULT_ADD_COINS;

//	private QplayAdView adView;

	private boolean isShowShare = false;

//	@Override
//	public void onPaymentDeny(int arg0, String arg1, int arg2, String arg3,
//			int arg4, String arg5, String arg6, String arg7) {
//
//	}
//
//	@Override
//	public void onPaymentFailure(int arg0, String arg1, int arg2, String arg3,
//			int arg4, String arg5, String arg6, String arg7) {
//
//		onToast("Thanh toán không thành công");
//
//	}
//
//	@Override
//	public void onPaymentSuccess(int type, String arg1, int arg2, String arg3,
//			int coin, String arg5, String arg6, String arg7) {
//		if (type == PaymentManager.PAYMENT_TYPE_SMS || type == PaymentManager.PAYMENT_TYPE_WAP_CHARGING) {
//			mAddCoins = coin * 2;
//		} else {
//			if (coin < 20000)
//				mAddCoins = (int) (coin * 2.1);
//			else if (coin < 50000) {
//				mAddCoins = (int) (coin * 2.2);
//			} else if (coin < 100000) {
//				mAddCoins = (int) (coin * 2.3);
//			} else if (coin < 200000) {
//				mAddCoins = (int) (coin * 2.4);
//			} else if (coin < 500000) {
//				mAddCoins = (int) (coin * 2.5);
//			} else
//				mAddCoins = (int) (coin * 2.5);
//		}
//		gameStore.buyGold(mAddCoins);
//		totalGold += mAddCoins;
//		totalGold_display.setText(" x " + String.valueOf(totalGold));
//		mTotalSnail.setText(" x " + String.valueOf(totalGold));
//		totalSnailPopupRemoveSkill.setText(" x " + String.valueOf(totalGold));
//
//		onToast("Bạn đã nạp thêm " + mAddCoins + " ốc");
//
//	}

	private void onToast(final String mString) {
		gameHandler.post(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(MainGame.this, mString, Toast.LENGTH_SHORT)
						.show();
			}
		});
	}

//	@Override
//	public void onFinishLoadingItem() {
//
//	}

	@Override
	public void onWindowFocusChanged(final boolean pHasWindowFocus) {
		super.onWindowFocusChanged(pHasWindowFocus);

		if (pHasWindowFocus) {
			if (!mGameLoaded) {
				this.doResume();
				isCreate = true;
			} else if (this.mPaused) {
				this.doResume();
			}
			isShowDialogue = false;
			this.mHasWindowFocused = true;
		} else {
			if (!isShowDialogue && !this.mPaused) {
				this.doPause();
			} else {
				isShowDialogue = false;
			}
			this.mHasWindowFocused = false;
		}

	}

	public void onResume() {
		super.onResume();

//		paymentUpdate.onResume();
//		QplayAchievementUserInfo.getInstance(this, this).onStopGame();
//		QplayAchievementUserInfo.getInstance(this, this).setPaymentManager(
//				paymentUpdate);

	}

	public void onStop() {
		super.onStop();
//		if (paymentUpdate != null) {
//			paymentUpdate.release();
//		}
	}

	public void onCreate(Bundle pbunlde) {
		super.onCreate(pbunlde);

		loadParam = new SunnetLoadParam(this);

		sVersionNumber = loadParam.getVersionCode();
		sVersionName = loadParam.getVersionName();
		NO_UPDATE = loadParam.isNoUpdate();
		DEFAULT_ITEM_PRODUCT_ID = loadParam.getItemProductID();
		DEFAULT_PRODUCT_ID = loadParam.getProductID();
		DEFAULT_CHANNEL_ID = loadParam.getChannelID();
		loadParam.doConfigNotShowLoading();

		if (HAS_PAYMENT) {
//			paymentUpdate = new PaymentManagerTakeItAll(this, SMS_EXTRA_CODE,
//					this);
//			paymentUpdate.prepareScratch(R.layout.card_main,
//					(ViewGroup) findViewById(R.id.layout_root),
//					R.id.txt_scratch_code, R.id.radio_scratch_vina,
//					R.id.radio_scratch_mobi, R.id.radio_scratch_viettel,
//					R.id.tbr_scratch_seri, R.id.txt_scratch_seri,
//					R.id.tv_scratch_description,
//					getString(R.string.payment_description_scratch));
//			paymentUpdate.prepareCoupon(R.layout.coupon_main,
//					(ViewGroup) findViewById(R.id.layout_coupon_root),
//					R.id.txt_coupon_code, R.id.tv_coupon_description,
//					getString(R.string.payment_description_coupon));
			
			// Khởi tạo hình thức thanh toán bằng thẻ
//			paymentUpdate.prepareCard(R.layout.card_main,
//			    (ViewGroup) findViewById(R.id.layout_root),
//			    R.id.txt_scratch_code, R.id.radio_group,
//			    R.id.radio_scratch_vina, R.id.radio_scratch_mobi,
//			    R.id.radio_scratch_viettel, R.id.radio_scratch_coupon,
//			    R.id.tbr_scratch_seri, R.id.txt_scratch_seri,
//			    R.id.tv_scratch_description, R.id.button_scratch,
//			    R.id.button_other, R.id.button_cancel,
//			    getString(R.string.payment_description_scratch));
//			
//			paymentUpdate.prepareSMS(getString(R.string.hoi_gui_sms),
//					DEFAULT_PREFIX_NUMBER);
//			paymentUpdate.setPaymentContent(DEFAULT_MESSAGE_CODE, "buy_coins");
//			if (loadParam.getChannelID().equals("1"))
//			    paymentUpdate.prepareWapCharging(getString(R.string.buy_game_text_web),15000);
//
//			paymentUpdate.buildPaymentMethodList();
		}
//		adView = (QplayAdView) findViewById(R.id.adView);
//		if (adView != null) {
//			adView.loadAd();
//		}

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start(UA_GOOGLE_ANALYTIC, 20, this);
		
		// Thông tin id của activity đăng nhập
//		LoginIDInfo loginIDInfo = new LoginIDInfo(R.layout.login,
//				R.id.text_login_name, R.id.text_password, R.id.check_remember,
//				R.id.button_login, R.id.button_regist, R.id.button_close,
//					"ADN");		
//		// Thông tin id của activity đăng ký
//		RegisterIDInfo registerIDInfo = new RegisterIDInfo(R.layout.register,
//					R.id.text_login_name, R.id.text_password,
//					R.id.text_confirm_password, R.id.rdb_male, R.id.rdb_female,
//					R.id.button_regist, R.id.button_close);
		// khai báo
//		mHighScore = new QplayHighScoreUserInfo(this, this, loginIDInfo,
//					registerIDInfo, paymentUpdate);
//		QplayAchievementUserInfo.getInstance(this, this).setDialogLayout(null,
//							"10.000 ốc.");
			
		// load thông tin tài khoản
//		mHighScore.prepareUserInfo();

	}

	@Override
	protected int getLayoutID() {
		return R.layout.main;
	}

	@Override
	protected int getRenderSurfaceViewID() {
		return R.id.rendersurfaceview;
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			AlertDialog.Builder alertboxExit = new AlertDialog.Builder(this);
			alertboxExit
					.setTitle(getResources().getString(R.string.title_exit));
			alertboxExit.setMessage(getResources()
					.getString(R.string.exit_game));
			alertboxExit.setNeutralButton(
					getResources().getString(R.string.ok),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							isShowDialogue = false;
							System.runFinalizersOnExit(true);
							System.exit(0);
						}

					});

			alertboxExit.setNegativeButton(
					getResources().getString(R.string.cancel), null);
			return alertboxExit.create();
		case 2:
			AlertDialog.Builder alertboxInfo = new AlertDialog.Builder(this);
			alertboxInfo.setTitle(getResources()
					.getString(R.string.title_about));
			alertboxInfo.setMessage(getResources().getString(
					R.string.message_about));
			alertboxInfo.setNegativeButton(
					getResources().getString(R.string.LS_CLOSE),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							isShowDialogue = false;
						}

					});
			return alertboxInfo.create();
		case 3:
			AlertDialog.Builder alertboxReportFree = new AlertDialog.Builder(
					this);
			alertboxReportFree.setTitle(getResources().getString(
					R.string.title_free));
			alertboxReportFree.setMessage(getResources().getString(
					R.string.message_free));
			alertboxReportFree.setNegativeButton(
					getResources().getString(R.string.ok),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							isShowDialogue = false;
						}

					});
			return alertboxReportFree.create();

		case 4:
			AlertDialog.Builder activePopup = new AlertDialog.Builder(this);
			activePopup.setTitle(getResources().getString(R.string.active));
			activePopup.setNeutralButton(getResources().getString(R.string.ok),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface arg0, int arg1) {
							activeGame();
						}

					});

			activePopup.setNegativeButton(
					getResources().getString(R.string.cancel), null);
			return activePopup.create();
		}

		return null;
	}

	private void activeGame() {
		if (totalGold >= 10000) {
			gameStore.setNewBie(false);
			gameStore.pay(10000);
			totalGold -= 10000;
			totalGold_display.setText(" x " + String.valueOf(totalGold));
			mTotalSnail.setText(" x " + String.valueOf(totalGold));
			totalSnailPopupRemoveSkill.setText(" x "
					+ String.valueOf(totalGold));

			onToast("Cảm ơn bạn đã kích hoạt game!\r\n Chúc bạn chơi game vui vẻ");
		} else {
			paySnail(true);
		}
	}

	private int resetAccount = -1;

	@Override
	public void onClick(MyTiledButton pButtonSprite, float pTouchAreaLocalX,
			float pTouchAreaLocalY) {
		switch (mGameStates) {
		case GAME_SELECT_ACCOUNT:
			switch (pButtonSprite.getID()) {
			case RESET_ACCOUNT_1:
				if (!isPopup) {
					showPopUpAccount();
					resetAccount = RESET_ACCOUNT_1 - 50;
				}
				break;

			case RESET_ACCOUNT_2:
				if (!isPopup) {
					showPopUpAccount();
					resetAccount = RESET_ACCOUNT_2 - 50;
				}
				break;

			case RESET_ACCOUNT_3:
				if (!isPopup) {
					showPopUpAccount();
					resetAccount = RESET_ACCOUNT_3 - 50;
				}
				break;

			default:
				if (!isPopup) {
					try {
						sTransitionScene.play();
					} catch (Exception e) {
					}
					ACCOUNT = pButtonSprite.getID();
					if (!isLoadedDataAccount[ACCOUNT]) {
						isLoadedDataAccount[ACCOUNT] = true;
						mGameSrotes[ACCOUNT].onLoadStep2(this);
					}
					setEquipmentScene();
				}
				break;
			}

			break;

		case GAME_SHOP:
			switch (pButtonSprite.getID()) {
			case SCROLL_LEFT:

				break;
			case SCROLL_RIGHT:

				break;
			default:
				break;
			}

			break;

		default:
			break;
		}
	}
	
//	private QplayHighScoreUserInfo mHighScore;
//	private static final int STAGE_DEFAULT = 1;
//	private static final int SCORE_SNAIL_DEFAULT = 10000;
	
//	private boolean checkShowScore() {
//		if (stage >= STAGE_DEFAULT) {
//			return true;
//		}
//		
//		return false;
//	}
	
//	private int calculateScore(final GameStore pGameStore) {
//		int score = 0;
//		
//		final int stage = pGameStore.getStage() + 1;
//		
//		score = stage * 1000000;
//		long time = pGameStore.getTime() / 1000;
//
//		long hour = time / 3600;
//		time = time % 3600;
//		long minus = time / 60;
//		time = time % 60;
//		long second = time;
//		
//		hour = parseInt((int)hour);
//		minus = parseInt((int)minus);
//		second = parseInt((int)second);
//		
//		score += (1000000 - (hour * 10000 + minus * 100 + second));
//		
//		return score;
//	}
//	
//	private int parseInt(final int pTime) {
//		final int value = (pTime / 10) * 10 + pTime % 10;
//		return value > 99 ? 99:value;
//	}

//	@Override
//	public void onLogoutSuccess(QplayHighScoreUserInfo arg0, int arg1) {
//		
//	}
//
//	@Override
//	public void onSendScoreDeny(QplayHighScoreUserInfo arg0, int arg1) {
//		try {
//			sTransitionScene.play();
//		} catch (Exception e) {
//		}
//		setAccountScene();
//		System.gc();
//	}
//
//	@Override
//	public void onSendScoreFailure(QplayHighScoreUserInfo arg0, int arg1) {
//		
//	}
//
//	@Override
//	public void onSendScoreSuccess(QplayHighScoreUserInfo arg0, int pType) {
//		if (pType == QplayHighScoreUserInfo.TYPE_SMS) {
//			try {
//				sTransitionScene.play();
//			} catch (Exception e) {
//			}
//			setAccountScene();
//			Runtime.getRuntime().gc();
//			return;
//		}
//		if (pType == QplayHighScoreUserInfo.TYPE_NETWORK) {
//			updateGold(SCORE_SNAIL_DEFAULT);
//		}
//		
//		isShowDialogue = true;
//		try {
//			mHighScore.openScoreActivity();
//		} catch (Exception e) {
//			AlertDialog.Builder alertBox = new AlertDialog.Builder(this);
//			alertBox.setNegativeButton(getString(R.string.cancel), null);
//			alertBox.setMessage(e.getMessage());
//			alertBox.setPositiveButton("OK", null);
//			alertBox.show();
//		}
//	}
//	@Override
//	public void onScoreViewClose(QplayHighScoreUserInfo arg0, int arg1) {
//		try {
//			sTransitionScene.play();
//			} catch (Exception e) {
//		}
//		setAccountScene();
//		Runtime.getRuntime().gc();
//	}

//	private void updateGold(int pPay) {
//		gameStore.pay(SCORE_SNAIL_DEFAULT);
//		totalGold -= SCORE_SNAIL_DEFAULT;
//		
//		totalGold_display.setText(String.valueOf(totalGold));
//
//		Coin_General[ACCOUNT] = totalGold;
//		Coin_Text[ACCOUNT].setText("Gold " + totalGold);
//		
//	}
	
//	@Override
//	public boolean onValidBeforeSendScore(QplayHighScoreUserInfo pHighScoreUserInfo, int arg1) {
//		if (totalGold >= SCORE_SNAIL_DEFAULT) {
//			return true;
//		}
//		isShowDialogue = true;
//		paymentUpdate.setPreDescription("Bạn không có đủ " + SCORE_SNAIL_DEFAULT + " ốc để khoe điểm cao.");
//		paymentUpdate.showDefaultPayment();
//		return false;
//	}
//
//	@Override
//	public void onAchievementReached(QplayAchievementUserInfo info,
//			QplayAchievementElement achievement, int type) {
//		QplayAchievementUserInfo.getInstance(this, this)
//				.showSendAchievementDialog(achievement);
//	}
//
//	@Override
//	public void onSendAchievementSuccess(QplayAchievementUserInfo info,
//			final QplayAchievementElement achievement, int type) {
//		if (type == QplayHighScoreUserInfo.TYPE_SMS) {
//			try {
//				sTransitionScene.play();
//			} catch (Exception e) {
//			}
//			setAccountScene();
//			Runtime.getRuntime().gc();
//			return;
//		}
//		if (type == QplayHighScoreUserInfo.TYPE_NETWORK) {
//			updateGold(SCORE_SNAIL_DEFAULT);
//			runOnUiThread(new Runnable() {
//
//				@Override
//				public void run() {
//					Toast.makeText(MainGame.this,
//							"Gửi danh hiệu thành công", Toast.LENGTH_LONG)
//							.show();
//					if (achievement != null) {
//						QplayAchievementUserInfo.getInstance(MainGame.this,
//								MainGame.this).openAchievementView(
//								achievement.getTypeId());
//					}
//				}
//			});
//		}
//		
//		isShowDialogue = true;
//	}

//	@Override
//	public void onSendAchievementFailure(QplayAchievementUserInfo info,
//			QplayAchievementElement achievement, int type) {
//		runOnUiThread(new Runnable() {
//
//			@Override
//			public void run() {
//				Toast.makeText(MainGame.this, "Gửi danh hiệu thất bại",
//						Toast.LENGTH_LONG).show();
//			}
//		});
//	}
//
//	@Override
//	public void onSendAchievementDeny(QplayAchievementUserInfo info,
//			QplayAchievementElement achievement, int type) {
//		// runOnUiThread(new Runnable() {
//		//
//		// @Override
//		// public void run() {
//		// Toast.makeText(MainActivity.this, "Hủy gửi danh hiệu",
//		// Toast.LENGTH_LONG).show();
//		// }
//		// });
//	}
//
//	@Override
//	public void onAchievementViewClose(QplayAchievementUserInfo client,
//			QplayAchievementElement achievement, int type) {
//
//	}
//
//	@Override
//	public boolean onValidBeforeSendAchievement(QplayAchievementUserInfo info,
//			QplayAchievementElement achievement, int type) {
//		if (totalGold >= SCORE_SNAIL_DEFAULT) {
//			return true;
//		}
//		isShowDialogue = true;
//		paymentUpdate.setPreDescription("Bạn không có đủ " + SCORE_SNAIL_DEFAULT + " ốc để khoe danh hiệu.");
//		paymentUpdate.showDefaultPayment();
//		return false;
//	}

}